删除元素及其子元素的所有 JavaScript 事件侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3222486/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:44:46  来源:igfitidea点击:

Remove all JavaScript event listeners of an element and its children?

javascripthtmlcss

提问by Tower

Is it possible to remove all event listeners of an element and its children? Something like:

是否可以删除元素及其子元素的所有事件侦听器?就像是:

myElem.removeEventListeners();

I need this because I have a complex element with events, and I need to create a copy of it -- like a static image that does not react to any events.

我需要这个,因为我有一个复杂的事件元素,我需要创建它的副本——就像一个对任何事件都没有反应的静态图像。

回答by gblazex

If you use cloneNode, the event listeners won't be copied.

如果使用cloneNode则不会复制事件侦听器。

If you want a robust solution your best bet is probably to write a wrapper to attach/detachlisteners, and keep track of them yourself. Something like Dean Edwards' addEvent.

如果你想要一个强大的解决方案,你最好的办法可能是为attach/detach听众编写一个包装器,并自己跟踪他们。类似于Dean Edwards 的 addEvent

回答by TNi

I do not know of one, and a search on Google didn't yield any obvious results. One easy, kludgy solution is to create a function that cycles through every event and sets it to null, such as

我不知道,在谷歌上搜索没有产生任何明显的结果。一个简单、笨拙的解决方案是创建一个函数来循环遍历每个事件并将其设置为null,例如

function removeEvents(obj)
{
    obj.onblur = null;
    obj.onchange = null;
    obj.onclick = null;
    // ...
}

Call this function as follows: removeEvents(myElem). A complete list of JavaScript event handlers can be found at http://www.elated.com/articles/events-and-event-handlers/.

调用该函数如下:removeEvents(myElem)。可以在http://www.elated.com/articles/events-and-event-handlers/找到 JavaScript 事件处理程序的完整列表。

Undoubtedly there is a more elegant way to write this function, but I don't know if there is a more elegant way to solve this problem. It would be lovely if someone knows of one. If you are binding events through a JavaScript library, such as jQuery, there may be other, better options.

无疑有更优雅的方式来写这个函数,但是不知道有没有更优雅的方式来解决这个问题。如果有人知道,那就太好了。如果您通过 JavaScript 库(例如 jQuery)绑定事件,那么可能还有其他更好的选择。