Copy from http://www.jb51.net/article/66111.htm
The examples in this article describe attachevent usage in JavaScript. Share to everyone for your reference. The specific analysis is as follows:
In general we add the event in JS, this is the
Obj.onclick=method
This way of binding events is compatible with mainstream browsers, but what if one element is added multiple times the same event?
?
123 |
obj.onclick=method1 obj.onclick=method2 obj.onclick=method3 |
If this is written, then only the last bound event, here is method3 will be executed, this time we can not use the onclick such writing, the protagonist changed the debut, in IE we can use the Attachevent method
?
123 |
btn1Obj.attachEvent( "onclick" ,method1); btn1Obj.attachEvent( "onclick" ,method2); btn1Obj.attachEvent( "onclick" ,method3); |
The use of the format is preceded by the event type, note that the need to add on, such as Onclick,onsubmit,onchange, the order of execution is
Method3->method2->method1
Unfortunately this Microsoft private method, Firefox and other browsers are not supported, fortunately they all support the standard AddEventListener method
?
123 |
btn1Obj.addEventListener( "click" ,method1, false ); btn1Obj.addEventListener( "click" ,method2, false ); btn1Obj.addEventListener( "click" ,method3, false ); |
Execution order is method1->method2->method3
?
1234567891011121314151617181920212223242526272829303132333435 |
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
"http://www.w3.org/1999/xhtml"
>
<title>attachEvent</title>
<script type=
"text/javascript"
>
//第一种方式(微软的私人方法)
function iniEvent() {
var btn = document.getElementById(
"btn"
);
btn.attachEvent(
"onclick"
, click1);
btn.attachEvent(
"onclick"
, click2);
btn.attachEvent(
"onclick"
, click3);
}
//第二种方式(火狐和其他浏览器)
function iniEvent2() {
var btn = document.getElementById(
"btn"
);
btn.addEventListener(
"click"
, click1,
false
);
btn.addEventListener(
"click"
, click2,
false
);
btn.addEventListener(
"click"
, click3,
false
);
}
function click1() {
alert(
‘click1‘
);
}
function click2() {
alert(
‘click2‘
);
}
function click3() {
alert(
‘click3‘
);
}
</script>
<body onload=
"iniEvent()"
>
<input type=
"button" id=
"btn" value=
"attachEvent" />
</body>
|
Attachevent events and AddEventListener events in JavaScript