js綁定事件和解除綁定事件

來源:互聯網
上載者:User

標籤:listen   注意   div   class   script   blog   需要   問題   click   

在js中綁定多個事件用到的是兩個方法:attachEvent和addEventListener,但是這兩個方法又存在差異性

  attachEvent方法  只支援IE678,不相容其他瀏覽器

  addEventListener方法   相容FirefoxGoogle,不相容IE8及以下

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和FirefoxGoogle的方法

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方法  只支援IE678,不相容其他瀏覽器

  removeEventListener方法   相容FirefoxGoogle,不相容IE8及以下

detachEvent方法寫法:

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


 

js綁定事件和解除綁定事件

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.