<!-- to assign a function to the onclick property of a DOM node element. --><divid="my-div">click</div><script>varmyelement=document.getElementById('my-div');myelement.onclick=function(){alert('Ouch!');alert('And double ouch!');};</script>
DOM event listeners
The best way to work with browser events is to use the event listener approach
outlined in DOM Level 2, where you can have many functions listening to an event.
When the event fires, all functions are executed.
// all linksvarall_links=document.getElementsByTagName('a');for(vari=0;i<all_links.length;i++){// loop all linksall_links[i].addEventListener('click',// event typefunction(e){// handlerif(!confirm('Sure you want to follow this link?')){e.preventDefault();}},false// don't use capturing);}
event 的类型
Mouse events
mouseup, mousedown, click (the sequence is mousedown-up-click),
dblclick
mouseover (mouse is over an element), mouseout (mouse was over an element but left it), mousemove
Keyboard events
keydown, keypress, keyup (occur in this sequence)
Loading/window events
load (an image or a page and all of its components are done loading), unload (user leaves the page), beforeunload (the script can provide the user with an option to stop the unload)
abort (user stops loading the page or an image in IE), error (a JavaScript error, also when an image cannot be loaded in IE)
resize (the browser window is resized), scroll (the page is scrolled), contextmenu (the right-click menu appears)
Form events
focus (enter a form field), blur (leave the form field)
change (leave a field after the value has changed), select (select text in a text field)
reset (wipe out all user input), submit (send the form)
drag events (dragstart, dragend, drop, and others)
touch events ( touchstart, touchmove, and touchend)
// 兼容IE和老浏览器的代码functioncallback(evt){// prep workevt=evt||window.event;vartarget=evt.target||evt.srcElement;// actual callback workconsole.log(target.nodeName);}// start listening for click eventsif(document.addEventListener){// Modern browsersdocument.addEventListener('click',callback,false);}elseif(document.attachEvent){// old IEdocument.attachEvent('onclick',callback);}else{document.onclick=callback;// ancient}