Home > Article > Web Front-end > Detailed explanation of binding events and unbinding events in js
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("春雨绵绵"); }This perfectly solves the compatibility problemIf there is a binding event, then there must be an unbinding event, but the unbinding event and the binding event Same, the evil IE will still make specializations
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); }Note: No matter it is tied You need to add on to set the event attachEvent or delete the event detachEvent. You do not need to add on for removeEventListenser and addEventListenser
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!