This article mainly introduces js binding events and unbinding events. It has good reference value. Next, let's take a look at it. This article mainly introduces the knowledge of js binding events and unbinding events. It has good reference value. Let's take a look at it with the small Editor.
Two methods are used to bind multiple events in js: attachEvent and addEventListener. However, there are differences between the two methods.
The attachEvent method only supports IE678 and is not compatible with other browsers.
The addEventListener method is compatible with Firefox Google and is not compatible with IE8 and earlier versions.
AddEventListener Method
P. addEventListener ('click', fn); p. addEventListener ('click', fn2); function fn () {console. log ("Spring rain");} function fn2 () {console. log ("wet everywhere ");}
AttachEvent Method
P. attachEvent ('onclick', fn); p. attachEvent ('onclick', fn2); function fn () {console. log ("Spring rain");} function fn2 () {console. log ("wet everywhere ");}
Note: Events bound to the attachEvent method include on, and events bound to the addEventListener do not include on.
Below I wrote a method compatible with IE and Firefox Google
Var 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 ("Spring rain ");}
In this way, the compatibility problem is solved perfectly.
If there is a binding event, there must be an unbinding event. However, the unbinding event is the same as the binding event. Internet Explorer will still be specialized.
The detachEvent method only supports IE678 and is not compatible with other browsers.
The removeEventListener method is compatible with Firefox Google and is not compatible with IE8 and earlier versions.
How to write the detachEvent method:
ele.detachEvent("onclick",fn);
RemoveEventListener:
ele.removeEventListener("click",fn);
Below I have written a compatibility Method 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: whether the event attachEvent is bound or the event detachEvent is deleted, it must be added to on. removeEventListenser and addEventListenser do not need to be added to on.
The above is a detailed description of binding events and unbinding events in js. For more information, see other related articles in the first PHP community!