JavaScript事件学习小结(二)js事件处理程序(2)

<input type="button" value="click me!"/> <script> var myBtn=document.getElementById("myBtn"); var handlerIE=function(){ alert("helloIE"); } var handlerDOM= function () { alert("helloDOM"); } myBtn.addEventListener("click",handlerDOM,false); myBtn.attachEvent("onclick",handlerIE); </script>

添加事件处理程序:现在为按钮添加两个事件处理函数,一个弹出“hello”,一个弹出“world

<script> var myBtn=document.getElementById("myBtn"); myBtn.attachEvent("onclick",function(){ alert("hello"); }); myBtn.attachEvent("onclick",function(){ alert("world"); }); </script>

note:这里运行效果值得注意一下:

IE8以下浏览器中先弹出“world”,再弹出“hello”。和DOM中事件触发顺序相反。

IE9及以上浏览器先弹出“hello”,再弹出“world”。和DOM中事件触发顺序相同了。

可见IE浏览器慢慢也走上正轨了。。。

删除事件处理程序:通过attachEvent添加的事件处理程序必须通过detachEvent方法删除,且参数一致。

和DOM事件一样,添加的匿名函数将无法删除。

所以为了能删除事件处理程序,代码可以这样写:

<input type="button" value="click me!"/> <script> var myBtn=document.getElementById("myBtn"); var handler= function () { alert("hello"); } myBtn.attachEvent("onclick",handler); myBtn.detachEvent("onclick",handler); </script>

note:IE事件处理程序中还有一个地方需要注意:作用域。

使用attachEvent()方法,事件处理程序会在全局作用域中运行,因此this等于window。

而dom2或dom0级的方法作用域都是在元素内部,this值为目标元素。

下面例子会弹出true。

<input type="button" value="click me!"/> <script> var myBtn=document.getElementById("myBtn"); myBtn.attachEvent("onclick",function(){ alert(this===window); }); </script>

在编写跨浏览器的代码时,需牢记这点。

IE7\8检测:

//判断IE7\8 兼容性检测 var isIE=!!window.ActiveXObject; var isIE6=isIE&&!window.XMLHttpRequest; var isIE8=isIE&&!!document.documentMode; var isIE7=isIE&&!isIE6&&!isIE8; if(isIE8 || isIE7){ li.attachEvent("onclick",function(){ _marker.openInfoWindow(_iw); }) }else{ li.addEventListener("click",function(){ _marker.openInfoWindow(_iw); }) }

以上所述是小编给大家介绍的JavaScript事件学习小结(二)js事件处理程序的相关知识,希望对大家有所帮助!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzspyj.html