Multiple methods to implement JS dynamic adding events

  • 2020-03-26 21:46:14
  • OfStack

Method 1. SetAttribute
Var obj = document. GetElementById (" obj ");
Obj. setAttribute("onclick", "javascript:alert(' test ');" );
However, IE does not support setAttribute to set some attributes, including object attributes, collection attributes, event attributes, that is to say setAttribute to set style, onclick, onmouseover these attributes is not available in IE.

Method 2. Use attachEvent and addEventListener
IE supports attachEvent, object. AttachEvent (event, function), for example:
 
obj.attachEvent("onclick", Foo); 
function Foo() 
{ 
alert(" test "); 
} 

Or obj.attachEvent("onclick", function(){alert(" test "); });
Other browsers support addEventListener, element.addEventListener(type,listener,useCapture,
 
obj.addEventListener("click", Foo, false); 
function Foo() 
{ 
alert(" test "); 
} 

Obj. addEventListener("click", function(){alert(" test "); }, false);
Notice that the attachEvent event has an on, such as onclick, and addEventListener has no on, such as click.
 
 Consider compatibility:  
if (window.attachEvent)//Compatible with IE
{ 
//IE event code
} 
else 
{ 
//Event code for other browsers
} 

There are two ways to add events, and we have to rewrite a generic add event function for the same method:

Version 1:
 
function addEvent(elm, evType, fn, useCapture) { 
if (elm.addEventListener) { 
elm.addEventListener(evType, fn, useCapture);//DOM2.0 
return true; 
} 
else if (elm.attachEvent) { 
var r = elm.attachEvent( ' on '  + evType, fn);//IE5+ 
return r; 
} 
else { 
elm['on' + evType] = fn;//DOM 0 
} 
} 

Version of the HTML5 working group:
 
var addEvent=(function(){ 
if(document.addEventListener){ 
return function(el,type,fn){ 
if(el.length){ 
for(var i=0;i<el.length;i++){ 
addEvent(el[i],type,fn); 
} 
}else{ 
el.addEventListener(type,fn,false); 
} 
}; 
}else{ 
return function(el,type,fn){ 
if(el.length){ 
for(var i=0;i<el.length;i++){ 
addEvent(el[i],type,fn); 
} 
}else{ 
el.attachEvent( ' on ' +type,function(){ 
return fn.call(el,window.event); 
}); 
} 
}; 
} 
})(); 

Method 3: event = function
Example: obj.onclick = Foo;
This way of binding events is compatible with major browsers, but what if you add the same event to an element multiple times?
 
obj.onclick=method1; 
obj.onclick=method2; 
obj.onclick=method3; 

So if I write this way, then only the last bound event, so this is method3 is going to be executed, so I should use method 2 to bind the event

Distinguish between IE6, IE7, IE8 methods:
 
var isIE=!!window.ActiveXObject; 
var isIE6=isIE&&!window.XMLHttpRequest; 
var isIE8=isIE&&!!document.documentMode; 
var isIE7=isIE&&!isIE6&&!isIE8; 
if (isIE){ 
  if (isIE6){ 
    alert( " ie6 " ); 
  }else if (isIE8){ 
    alert( " ie8 " ); 
  }else if (isIE7){ 
    alert( " ie7 " ); 
  } 
} 

Related articles: