如何从 Javascript 中的元素中删除单击事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6717960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove a click event from an element in Javascript?
提问by Stewart Alan
I have a <div>
element that has a click event attached to it using the following code:
我有一个<div>
元素,它使用以下代码附加了一个点击事件:
var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);
At a later point I copy the element and add it to another part of the DOM
, but need to first remove the click
event
稍后我复制该元素并将其添加到 的另一部分DOM
,但需要先删除该click
事件
var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);
I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.
我不确定如何引用侦听器,到目前为止我没有尝试从元素中删除事件。
Any ideas?
有任何想法吗?
Cheers
干杯
Stewart
斯图尔特
采纳答案by KooiInc
Move the anonymous click handler function out of the addEventListener
call:
将匿名点击处理函数移出addEventListener
调用:
var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);
after which you should be able to:
之后你应该能够:
var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);