如何删除元素中的所有侦听器?
我有一个按钮,我向其中添加了一些 eventlistners
:
document.getElementById("btn").addEventListener("click", funcA, false);
document.getElementById("btn").addEventListener("click", funcB, false);
document.getElementById("btn").addEventListener("click", funcC, false);
document.getElementById("btn").addEventListener("blur" , funcD, false);
document.getElementById("btn").addEventListener("focus", funcE, false);
<button id="btn">button</button>
我可以通过以下方式删除它们:
document.getElementById("btn").removeEventListener("click",funcA);
如果我想立即删除所有侦听器,或者我没有函数引用(<代码>funcA)?有没有办法做到这一点,或者我必须将它们一一删除?
I have a button, and I added some eventlistners
to it:
document.getElementById("btn").addEventListener("click", funcA, false);
document.getElementById("btn").addEventListener("click", funcB, false);
document.getElementById("btn").addEventListener("click", funcC, false);
document.getElementById("btn").addEventListener("blur" , funcD, false);
document.getElementById("btn").addEventListener("focus", funcE, false);
<button id="btn">button</button>
I can remove them by:
document.getElementById("btn").removeEventListener("click",funcA);
What if I want I want to remove all listeners at once, or I don't have the function reference (funcA
)? Is there a way of doing that, or I have to remove them one by one?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为最快的方法是克隆节点,这将删除所有事件侦听器:
请小心,因为这也会清除相关节点的所有子元素上的事件侦听器,因此如果您想保留您必须一次显式地删除一个侦听器。
I think that the fastest way to do this is to just clone the node, which will remove all event listeners:
Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.
如果您使用的是 jquery 事件,则可以在一行中完成此操作:
对于 jQuery 事件 (
.on()
):对于本机 javascript 事件 (
.addEventListener()
):这是一个示例:
http://jsfiddle.net/LkfLezgd/3/
If you’re using jquery events, this can be done in one line:
For jQuery events (
.on()
):For native javascript events (
.addEventListener()
):Here’s an example:
http://jsfiddle.net/LkfLezgd/3/
这是一个同样基于cloneNode的函数,但可以选择仅克隆父节点并移动所有子节点(以保留其事件侦听器):
删除一个元素上的事件侦听器:
删除事件侦听器在一个元素及其所有子元素上:
如果您需要保留对象本身,因此无法使用
cloneNode
,那么您必须包装addEventListener
函数并跟踪您自己的听众列表,例如这个答案。Here's a function that is also based on
cloneNode
, but with an option to clone only the parent node and move all the children (to preserve their event listeners):Remove event listeners on one element:
Remove event listeners on an element and all of its children:
If you need to keep the object itself and therefore can't use
cloneNode
, then you have to wrap theaddEventListener
function and track the listener list by yourself, like in this answer.