Home  >  Article  >  Web Front-end  >  How to unbind events in javascript

How to unbind events in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-04-16 16:43:365185browse

Method: 1. Use the "object name.onclick=null" statement; 2. Use the "object name.removeEventListener(type, function(){},false)" statement; 3. Use the "object.detachEvent" statement. (type, name)" statement.

How to unbind events in javascript

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

Encapsulate a compatibility event binding method Depending on the needs, sometimes the event must be contacted after the event binding is triggered.

Unbinding event method:

1. Unbinding onclick

 element.onclick = false/''/null

Instance

<p></p>
 var p = document.getElementByTagName("p")[0]; 
    p.onclick = function () {
    console.log("a");
    p.onclick = null; 
}

2. Unbinding addEventListener(type,function() {}, false),

Use remove to cancel

To cancel addEventListener(type, function(){}, false), the event type, function, and false must correspond one to one

Wrong way to cancel

var p = document.getElementByTagName("p");
p.addEventListener(&#39;click&#39;,function(){
    console.log("a");
},false)
p.removeEventListener(type,(function(){console.log("a");}),false)

This situation cannot be solved

Correct way to cancel

function test(){
    console.log("a");
}
p.addEventListener(&#39;click&#39;,test,false);
p.removeEventListener(&#39;click&#39;,test,false);

3. Release attachEvent('on' type,function(){ }), use detachEvent('on' type, function(){}) to release

function test(){}
obj.attachEvent(&#39;on&#39;+ type,test);
obj.detachEvent(&#39;on&#39;+type,test)

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to unbind events in javascript. 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