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.
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('click',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('click',test,false); p.removeEventListener('click',test,false);
3. Release attachEvent('on' type,function(){ }), use detachEvent('on' type, function(){}) to release
function test(){} obj.attachEvent('on'+ type,test); obj.detachEvent('on'+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!