Behavior of removeEventListener

戏子无情 提交于 2020-01-12 14:26:42

问题


Please check the below code,

var clickfn = function(){
 alert("clicked");                    
}
document.getElementById("div1").addEventListener("click",clickfn,true);
clickfn = function(){  };
document.getElementById("div1").removeEventListener("click");

http://jsfiddle.net/qUtzL/4/

Why does the removeEventListener does not work?

Thanks!


回答1:


removeEventListener takes 2 parameters, the event, and the function to remove.
This should work:

document.getElementById("div1").removeEventListener("click", clickfn);

Also, the function you're executing is empty.

var clickfn = function(){  };



回答2:


You have to specify the exact function you've specified to addEventListener as the second argument. If you specified the third useCapture argument, you'll have to specify the same and equivalent to removeEventListener as well.

For example:

function myFunc(event){ alert(event.target.textContent); }

var myElement=document.getElementById('myElement');

//Add EventListener
myElement.addEventListener('click', myFunc, false );

/* ... */

//Remove EventListener
myElement.removeEventListener('click', myFunc, false );

↪ View an example at jsFiddle

You can find more information at the Mozilla Developer wiki.



来源:https://stackoverflow.com/questions/13474370/behavior-of-removeeventlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!