Home > Web Front-end > JS Tutorial > body text

How to unbind events in javascript

醉折花枝作酒筹
Release: 2023-01-05 16:09:26
Original
5182 people have browsed it

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
Copy after login

Instance

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

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)
Copy after login

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);
Copy after login

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)
Copy after login

[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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template