js绑定事件和解绑事件

在js中绑定多个事件用到的是两个方法:attachEvent和addEventListener,可是这两个方法又存在差别性javascript

  attachEvent方法  只支持IE678,不兼容其余浏览器

  addEventListener方法   兼容火狐谷歌,不兼容IE8及如下
java

addEventListener方法浏览器

div.addEventListener('click',fn);
div.addEventListener('click',fn2);
function fn(){ console.log("春雨绵绵"); }
function fn2(){
                console.log("处处潮湿"); }
 

attachEvent方法spa

div.attachEvent('onclick',fn);
div.attachEvent('onclick',fn2);
function fn(){ console.log("春雨绵绵"); }
function fn2(){
                console.log("处处潮湿");
            }

注意点:attachEvent方法绑定的事件是带on的,addEventListener绑定的事件是不带on的code

下面我写了一个兼容了IE和火狐谷歌的方法blog

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仍是会搞特殊化ip

  detachEvent方法  只支持IE678,不兼容其余浏览器

  removeEventListener方法   兼容火狐谷歌,不兼容IE8及如下
rem

detachEvent方法写法:get

ele.detachEvent("onclick",fn);

removeEventListener的写法:

ele.removeEventListener("click",fn);

下面我写了一个兼容性的方法给你们参考,实现也是很简单

function remove(str,ele,fn){
				ele.detachEvent?ele.detachEvent("on"+str,fn):ele.removeEventListener(str,fn);
			}

  注意点:无论是绑定事件attachEvent仍是删除事件detachEvent都是要加on的,removeEventListenser和addEventListenser则不须要加on

相关文章
相关标签/搜索