This article mainly introduces the relevant knowledge of js binding events and unbinding events. Has very good reference value. Let's take a look at it with the editor
There are two methods used to bind multiple events in js: attachEvent and addEventListener, but there are differences between these two methods
attachEvent method only supports IE678, not compatible with other browsers
##addEventListener method compatible with Firefox and Google, not compatible with IE8 and below
addEventListener method
p.addEventListener('click',fn); p.addEventListener('click',fn2); function fn(){ console.log("春雨绵绵"); } function fn2(){ console.log("到处潮湿"); }
attachEvent method
p.attachEvent('onclick',fn); p.attachEvent('onclick',fn2); function fn(){ console.log("春雨绵绵"); } function fn2(){ console.log("到处潮湿"); }
Note: The event bound by the attachEvent method is with on, and the event bound by addEventListener is without on.
I wrote an example below that is compatible with IE And Firefox Google's methodvar p=document.getElementsByTagName("p")[0]; addEvent('click',p,fn) function addEvent(str,ele,fn){ ele.attachEvent?ele.attachEvent('on'+str,fn):ele.addEventListener(str,fn); } function fn(){ console.log("春雨绵绵"); }
detachEvent method only supports IE678 and is not compatible with other browsers
removeEventListener method Compatible with Firefox and Google, not compatible with IE8 and below
##detachEvent method writing:
ele .detachEvent("onclick",fn);ele.removeEventListener("click ",fn);
I wrote a compatibility method below for your reference. The implementation is also very simple
function remove(str,ele,fn){ ele.detachEvent?ele.detachEvent("on"+str,fn):ele.removeEventListener(str,fn); }
The above is the detailed content of Detailed explanation of binding events and unbinding events in js. For more information, please follow other related articles on the PHP Chinese website!