Compatible Code for Unbinding Arbitrary Events with js Arbitrary Elements

Keywords: Javascript IE Google Firefox

hmtl code:
<input type="button" value="Button" id="btn"/>
<input type="button" value="The event of killing the first button" id="btn2"/>
There are three kinds of kidnapping incidents:
 
Note: In what way events are bound, events should be unbound in the corresponding way
1. Unbundling events (ON s supported by IE, Google and Firefox)
Object. on event name = event handler - > bound event
Object. on event name = null;
 my$("btn").onclick=function () {
   console.log("I'm wretched.");
 };
 my$("btn2").onclick=function () {
   //1.Deregulation
   my$("btn").onclick=null;
 };

 

2. Unbundling events (Google Firefox supports IE does not support)
Object. addEventListener("No on event type", "Named function, false); - - Binding events
Object. removeEventListener("event type without on", function name, false);
 
function f1() {
   console.log("First");
 }
 function f2() {
   console.log("The second");
 }

 my$("btn").addEventListener("click",f1,false);
 my$("btn").addEventListener("click",f2,false);

 //Click on the second button to unbind the first click event of the first button
 my$("btn2").onclick=function () {
   //When Unbundling Events,When events need to be bound,Using named functions
   my$("btn").removeEventListener("click",f1,false);
 };

 

3. Unbundling events (note that this is supported by ie and not supported by others)
Object. attachEvent (on event type, named function); - - Binding event
Object. detachEvent (on event type, function name);
function f1() {
    console.log("First");
  }
  function f2() {
    console.log("The second");
  }
  my$("btn").attachEvent("onclick",f1);
  my$("btn").attachEvent("onclick",f2);

  my$("btn2").onclick=function () {
      my$("btn").detachEvent("onclick",f1);
  };

 

In order to solve the compatibility between IE and Google Firefox:

 

//Compatibility of unbound events
  //For any element,Unbundling corresponding events
  //element element  type Event type fnName Event Handling Functions
  function removeEventListener(element,type,fnName) {
    if(element.removeEventListener){
      element.removeEventListener(type,fnName,false);
    }else if(element.detachEvent){
      element.detachEvent("on"+type,fnName);
    }else{
      element["on"+type]=null;
    }
  }

 

 

 

 

 

Posted by phpbaby2009 on Thu, 21 Mar 2019 11:00:52 -0700