Javascript 删除匿名事件侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3106605/
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
Removing an anonymous event listener
提问by erikvold
Is there anyway to remove an event listener added like this:
无论如何要删除这样添加的事件侦听器:
element.addEventListener(event, function(){/* do work here */}, false);
Without replacing the element?
不更换元素?
采纳答案by Joe
There is no way to cleanly remove an event handler unless you stored a reference to the event handler at creation.
除非您在创建时存储了对事件处理程序的引用,否则无法彻底删除事件处理程序。
I will generally add these to the main object on that page, then you can iterate and cleanly dispose of them when done with that object.
我通常会将这些添加到该页面上的主对象中,然后您可以在完成该对象后迭代并干净地处理它们。
回答by icktoofay
You could remove the event listener like this:
您可以像这样删除事件侦听器:
element.addEventListener("click", function clicked() {
element.removeEventListener("click", clicked, false);
}, false);
回答by icktoofay
Anonymous boundevent listeners
匿名绑定事件监听器
The easiest way to remove all event listeners for an element is to assign its outerHTMLto itself. What this does is send a string representation of the HTML through the HTML parser and assign the parsed HTML to the element. Because no JavaScript is passed, there will be no bound event listeners.
删除元素的所有事件侦听器的最简单方法是将其分配outerHTML给自身。它的作用是通过 HTML 解析器发送 HTML 的字符串表示,并将解析后的 HTML 分配给元素。因为没有传递 JavaScript,所以不会有绑定的事件监听器。
document.getElementById('demo').addEventListener('click', function(){
alert('Clickrd');
this.outerHTML = this.outerHTML;
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>
Anonymous delegatedevent listeners
匿名委托事件侦听器
The one caveat is delegated event listeners, or event listeners on a parent element that watch for every event matching a set of criteria on its children. The only way to get past that is to alter the element to not meet the criteria of the delegated event listener.
一个警告是委托的事件侦听器,或父元素上的事件侦听器,它们监视每个与其子元素上的一组条件匹配的事件。解决这个问题的唯一方法是更改元素以使其不满足委托事件侦听器的标准。
document.body.addEventListener('click', function(e){
if(e.target.id === 'demo') {
alert('Clickrd');
e.target.id = 'omed';
}
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>
回答by w35l3y
You may try to overwrite element.addEventListenerand do whatever you want.
Something like:
您可以尝试覆盖element.addEventListener并做任何您想做的事情。
就像是:
var orig = element.addEventListener;
element.addEventListener = function (type, listener) {
if (/dontwant/.test(listener.toSource())) { // listener has something i dont want
// do nothing
} else {
orig.apply(this, Array.prototype.slice.apply(arguments));
}
};
ps.: it is not recommended, but it will do the trick (haven't tested it)
ps.: 不推荐,但可以解决问题(还没有测试过)
回答by general64
Edit:As Manngosuggested per comment, you should use .off()instead of .unbind()as .unbind()is deprecated as of jQuery 3.0 and superseded since jQuery 1.7.
编辑:正如Manngo每条评论所建议的那样,您应该使用.off ()而不是.unbind()因为.unbind()从 jQuery 3.0 起已被弃用,并自 jQuery 1.7 起被取代。
Even though this an old question and it does not mention jQuery I will post my answer here as it is the first result for the searchterm 'jquery remove anonymous event handler'.
即使这是一个老问题并且它没有提到 jQuery,我也会在这里发布我的答案,因为它是搜索词 'jquery remove anonymous event handler'的第一个结果。
You could try removing it using the .off()function.
您可以尝试使用.off()函数删除它。
$('#button1').click(function() {
alert('This is a test');
});
$('#btnRemoveListener').click(function() {
$('#button1').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">Click me</button>
<hr/>
<button id="btnRemoveListener">Remove listener</button>
However this only works if you've added the listener using jQuery - not .addEventListener
但是,这仅在您使用 jQuery 添加侦听器时才有效 - 而不是.addEventListener
Found this here.
在这里找到了这个。
回答by Manngo
Old Question, but here is a solution.
老问题,但这里有一个解决方案。
Strictly speaking you can't remove an anonymous event listener unless you store a reference to the function. Since the goal of using an anonymous function is presumably not to create a new variable, you could instead store the reference in the element itself:
严格来说,除非您存储对该函数的引用,否则您无法删除匿名事件侦听器。由于使用匿名函数的目的大概不是创建新变量,因此您可以将引用存储在元素本身中:
element.addEventListener('click',element.fn=function fn() {
// Event Code
}, false);
Later, when you want to remove it, you can do the following:
稍后,当您想要删除它时,您可以执行以下操作:
element.removeEventListener('click',element.fn, false);
Remember, the third parameter (false) must have the samevalue as for adding the Event Listener.
请记住,第三个参数 ( false) 的值必须与添加事件侦听器的值相同。
However, the question itself begs another: why?
然而,问题本身又引出了另一个问题:为什么?
There are two reasons to use .addEventListener()rather than the simpler .onsomething()method:
使用.addEventListener()而不是更简单的.onsomething()方法有两个原因:
First, it allows multipleevent listeners to be added. This becomes a problem when it comes to removing them selectively: you will probably end up naming them. If you want to remove them all, then @tidy-giant's outerHTMLsolution is excellent.
首先,它允许添加多个事件侦听器。在有选择地删除它们时,这会成为一个问题:您可能最终会命名它们。如果您想将它们全部删除,那么@tidy-giant 的outerHTML解决方案非常好。
Second, you do have the option of choosing to capture rather than bubble the event.
其次,您确实可以选择捕获而不是冒泡事件。
If neither reason is important, you may well decide to use the simpler onsomethingmethod.
如果这两个原因都不重要,您很可能决定使用更简单的onsomething方法。
回答by kennebec
Assigning event handlers with literal functions is tricky- not only is there no way to remove them, without cloning the node and replacing it with the clone- you also can inadvertantly assign the same handler multiple times, which can't happen if you use a reference to a handler. Two functions are always treated as two different objects, even if they are character identical.
使用文字函数分配事件处理程序很棘手 - 不仅无法删除它们,而无需克隆节点并将其替换为克隆节点 - 您还可能在不经意间多次分配相同的处理程序,如果您使用对处理程序的引用。两个函数始终被视为两个不同的对象,即使它们的字符相同。
回答by Ice101781
The following worked well enough for me. The code handles the case where another event triggers the listener's removal from the element. No need for function declarations beforehand.
以下对我来说效果很好。该代码处理另一个事件触发侦听器从元素中移除的情况。无需事先声明函数。
myElem.addEventListener("click", myFunc = function() { /*do stuff*/ });
/*things happen*/
myElem.removeEventListener("click", myFunc);
回答by uingtea
If you're using jQuery try offmethod
如果您使用 jQuery tryoff方法
$("element").off("event");
回答by Compunction
Jquery .off() method removes event handlers that were attached with .on()
Jquery .off() 方法删除与 .on() 附加的事件处理程序

