删除特定类型的所有事件侦听器 [英] Remove All Event Listeners of Specific Type

查看:94
本文介绍了删除特定类型的所有事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除使用 addEventListener()添加的特定类型的所有事件侦听器。我看到的所有资源都表示你需要这样做:

I want to remove all event listeners of a specific type that were added using addEventListener(). All the resources I'm seeing are saying you need to do this:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown',specific_function);

但是,我想要清除它,而不知道它是什么,像这样: p>

But I want to be able to clear it without knowing what it is currently, like this:

elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown');


推荐答案

这是不可能没有拦截 addEventListener 调用并跟踪监听器或使用允许这样的功能的库不幸。如果可以访问侦听器集合,但功能未实现

That is not possible without intercepting addEventListener calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.

最近可以做的是通过克隆元素来删除所有的侦听器,而不会克隆侦听器集合。

The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.

注意:这也将删除元素子节点上的侦听器。

var el = document.getElementById('el-id'),
    elClone = el.cloneNode(true);

el.parentNode.replaceChild(elClone, el);

这篇关于删除特定类型的所有事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆