首先看下addEventListener()事件代码
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 5 <title>test54</title> 6 </head> 7 <body> 8 <input type="button" id="myBtn" value="点 击" name="btnName" /> 9 <script type="text/javascript" src="test54.js"></script> 10 </body> 11 </html>
1 var btn = document.getElementById("myBtn"); 2 var handler = function() { 3 console.log(this.id); 4 console.log(this === window);//false 5 }; 6 btn.addEventListener("click", handler, false); 7 //btn.removeEventListener("click", handler, false);
然后看看attachEvent()事件代码
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> 5 <title></title> 6 </head> 7 <body> 8 <input type="button" id="myBtn" value="点 击" name="btnName" /> 9 <script type="text/javascript" src="test55.js"></script> 10 </body> 11 </html>
1 //only ie 2 var btn = document.getElementById("myBtn"); 3 var handler = function() { 4 console.log("Clicked"); 5 console.log(this === window); //true 6 console.log("Hello world!!!"); //IE9一下会出现输出倒序问题,123->321 7 }; 8 btn.attachEvent("onclick", handler); 9 btn.detachEvent("onclick", handler);
可以看出addEventListener()事件处理程序会在其所属元素的作用域内运行,而attachEvent()事件处理程序会在全局作用域中运行(this等于window),并且在IE9以下版本里会出现输出倒序问题。