The running environment of the event handler
var div=document.getElementsByTagName('div')[0];
1.1 ele. Onxxx = function (event) {}
The program tihs points to the DOM element itself
div.onclick=function(){
console.log(this);
}//div
Copy the code
/ / 1.2. Obj. AddEventListener (type, fn, false);
// the program tihs points to the DOM element itself
div.addEventListener('click',function(){ console.log(this) },false); //divCopy the code
1.3. Obj. AttachEvent (‘ on ‘+ type, fn);
Program pointing to window
Make the program point to div
div.attachEvent('onclick',function(){ handle.call(div); }); function handle(){ // // this. Point to div // // event handler}Copy the code
** Encapsulate compatible addEvent(Elem, Type, Handle); Function addEvent(elem,type,handle) {if(elem.adDeventListener) {elem.adDeventListener (type,handle,false); }else if(elem.attachEvent) { elem.attachEvent('on'+type,function(){ handle.call(elem); }) }else{ elem['on'+type] = handle; //ele.on-xxx=function(event){} } }Copy the code
Remove the event handler
var div=document.getElementsByTagName('div')[0];
Copy the code
2.1 ele. Onclick = false/’/null;
div.onclick = function(){ console.log('a'); this.onclick=null; } div. Onclick = null; Invalidate eventsCopy the code
2.2 ele. RemoveEventListener (type, fn, false);
div.addEventListener('click',test,false); Function test(){// Name the function console.log('a'); } div.removeEventListener('click',test,false); // Bind a particular handler for a particular event type of an objectCopy the code
2.3 ele. DetachEvent (‘ on ‘+ type, fn);
If you bind an anonymous function, you cannot undo it