方法:1、使用“對(duì)象名.onclick=null”語(yǔ)句;2、使用“對(duì)象名.removeEventListener(type,function(){},false)”語(yǔ)句;3、使用“對(duì)象.detachEvent(類(lèi)型,名稱(chēng))”語(yǔ)句。
本教程操作環(huán)境:windows7系統(tǒng)、javascript1.8.5版、Dell G3電腦。
封裝一個(gè)兼容性事件綁定方法 應(yīng)需求有時(shí)候事件綁定觸發(fā)后就要接觸事件。
解除事件綁定方法:
1、onclick解除
element.onclick = false/''/null
實(shí)例
<p></p> var p = document.getElementByTagName("p")[0]; p.onclick = function () { console.log("a"); p.onclick = null; }
2、解除addEventListener(type,function(){},false),
使用remove解除
解除addEventListener(type,function(){},false),必須事件類(lèi)型、函數(shù)、false一一對(duì)應(yīng)
錯(cuò)誤的解除方式
var p = document.getElementByTagName("p"); p.addEventListener('click',function(){ console.log("a"); },false) p.removeEventListener(type,(function(){console.log("a");}),false)
這種情況是解除不了的
正確的解除方式
function test(){ console.log("a"); } p.addEventListener('click',test,false); p.removeEventListener('click',test,false);
3、解除attachEvent('on'+ type,function(){}),用 detachEvent('on'+type,function(){})解除
function test(){} obj.attachEvent('on'+ type,test); obj.detachEvent('on'+type,test)
【推薦學(xué)習(xí):javascript高級(jí)教程】