在js中綁定多個事件用到的是兩個方法:attachEvent和addEventListener,但是這兩個方法又存在差異性
addEventListener方法
div.addEventListener('click',fn);
div.addEventListener('click',fn2);
function fn(){ console.log("春雨綿綿"); }
function fn2(){ console.log("到處潮濕"); }
attachEvent方法
div.attachEvent('onclick',fn); div.attachEvent('onclick',fn2); function fn(){ console.log("春雨綿綿"); } function fn2(){ console.log("到處潮濕"); }
注意點:attachEvent方法綁定的事件是帶on的,addEventListener綁定的事件是不帶on的
下面我寫了一個兼容了IE和火狐谷歌的方法
var div=document.getElementsByTagName("div")[0]; addEvent('click',div,fn) function addEvent(str,ele,fn){ ele.attachEvent?ele.attachEvent('on'+str,fn):ele.addEventListener(str,fn); } function fn(){ console.log("春雨綿綿"); }
這樣就完美的解決了兼容性的問題
有綁定事件的話,那就肯定有解綁事件,但是解綁事件和綁定事件一樣,萬惡的IE還是會搞特殊化
detachEvent方法寫法:
ele.detachEvent("onclick",fn);
removeEventListener的寫法:
ele.removeEventListener("click",fn);
下面我寫了一個兼容性的方法給大家參考,實現也是很簡單
1
2
3
|
function
remove(str,ele,fn){
ele.detachEvent?ele.detachEvent(
"on"
+str,fn):ele.removeEventListener(str,fn);
}
|
注意點:不管是綁定事件attachEvent還是刪除事件detachEvent都是要加on的,removeEventListenser和addEventListenser則不需要加on