Yuanwen Http://www.jb51.net/article/32511.htm wrote AddEventListener and attachevent different blog posts, but most of them focus on the former is Firefox chrome, The latter only exists in the IE series write AddEventListener and attachevent differences in a lot of posts, but most of the focus on the former is Firefox Chrome, the latter only exists in the IE series.
Recently, when writing an event proxy, I encountered a bug that found that in addition to this, the AddEventListener and attachevent functions are not the same in the runtime context.
A simple demo is used to describe this difference:
Copy CodeThe code is as follows:
<<meta http-equiv= "Content-type" content= "Text/html;charset=utf-8"/>
<<title> Testing </title>
<<body>
<div id= "Div1" >
<a href= "#" id= "A1" >test1</a>
</div>
<<div id= "Div2" >
<a href= "#" id= "A2" >test2</a>
</div>
</body>
<<script type= "Text/javascript" >
var testgolb = "diff"; Define a global variable
var a1 = document.getElementById ("A1");
var a2 = document.getElementById ("A2");
function Geteleid (e) {
Body ...
alert (this.id);
alert (THIS.TESTGOLB);
}
A1.onclick = Geteleid;
if (a2.attachevent) {
A2.attachevent ("onclick", Geteleid);
}else{
A2.addeventlistener (' click ', Geteleid);
}
</script>
Click Test1
First alert under Chrome: "A1", Second alert: "Undefined"
Firefox First alert: "A1", Second alert: "Undefined"
First Alert in IE: "A1", Second alert: "Undefined"
This is good to understand, this time the this point #a1 this DOM, so the alert ID is #a1的id "A1", and then in this, and there is no testgolb this variable, so is undefined
Click Test2
First alert under Chrome: "A1", Second alert: "Undefined"
Firefox First alert: "A1", Second alert: "Undefined"
First Alert in IE: "Undefined", Second alert: "diff"
Chrome and Firefox are consistent when they click Test1, and IE is different. When using the Attachevent binding event, this point in the function is to window, not the DOM of the event, so the first alert value is undefined, and the value of This.testglob is diff.
AddEventListener and attachevent do not have the same "reprint" in the execution function that they are bound to