Home >Web Front-end >JS Tutorial >Detailed explanation of binding events and unbinding events in js

Detailed explanation of binding events and unbinding events in js

零下一度
零下一度Original
2017-04-28 09:48:251576browse

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 method

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("春雨绵绵");
      }

This perfectly solves the compatibility problem

If 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);

##How to write removeEventListener:

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn