Method 1, setAttribute var obj = document.getElementById("obj");
obj.setAttribute("onclick", "javascript:alert('test');");
However, IE does not support using setAttribute to set certain attributes, including object attributes, collection attributes, and event attributes. That is to say, using setAttribute to set style, onclick, and onmouseover attributes does not work 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 write obj.attachEvent("onclick", function(){alert("Test");});
Other browsers Support addEventListener, element.addEventListener(type,listener,useCapture,
obj.addEventListener("click", Foo, false);
function Foo()
{
alert("test");
}
Same as well Can be written together obj.addEventListener("click", function(){alert("test");}, false);
Note that the attachEvent event has on, such as onclick, while the addEventListener does not have on, such as click.
Consider compatibility:
if (window.attachEvent )//Compatible with IE
{
//Event code of IE
}
else
{
//Event code of other browsers
}
There are two methods of adding events above. In order to use the same method of adding events, we have to rewrite a general adding event function:
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
}
}
HTML5 working group version:
var addEvent=(function(){
if(document.addEventListener){
return function(el,type,fn){
if(el.length){
for(var i=0;iaddEvent(el[i],type,fn);
}
}else{
el.addEventListener(type, fn,false);
}
};
}else{
return function(el,type,fn){
if(el.length){
for(var i =0;iaddEvent(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 mainstream browsers, but if you add multiple What about the same event?
obj.onclick=method1;
obj.onclick=method2;
obj.onclick=method3;
If written like this, only the last bound event, here method3 will be executed, and the method should be used at this time Two methods for event binding
Differentiate methods between IE6, IE7 and IE8:
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″); ”ie8″);
}else if (isIE7){
alert(”ie7″);
}
}