jQuery off方法是否删除通过addEventListener添加的事件侦听器? [英] Does jQuery off method remove event listeners added with addEventListener?

查看:306
本文介绍了jQuery off方法是否删除通过addEventListener添加的事件侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个旧代码,并且在代码中看到,在同一元素上有很多用javascript addEventListener添加的事件,有些是用jQuery.on()添加的,但是在detach方法中,仅使用jQuery. off()删除它们.因此,我想知道这段代码是否会按编写它的人们的预期工作(从dom元素中删除所有事件),或者将不会删除添加有javascript的事件.

I am working on an old code and I have seen in the code that there are many events added with javascript addEventListener and some added with jQuery.on() on the same element but in the detach method it is used only jQuery.off() to remove them. So I was wondering if this code will work as the guys that wrote it expected (to remove all events from the dom element) or the events added with javascript won't be removed.

推荐答案

不是.

如果调查本机removeEventListener api,则可以看到它期望成功删除原始回调.据我所知,还没有删除节点上所有事件侦听器的本地方法.

If you investigate the native removeEventListener api you can see that it expects the original callback for a successful removal. As far as I'm aware, there is no native way for removing all event listeners on a node.

jQuery充当了其大部分工作的中介.这样做是为了使它可以使用onoff之类的东西来保持对其api的控制.

jQuery acts as an intermediary for much of what it does. It does this so that it can maintain control of its api with things like on and off.

如果您以跟踪添加的方式编写代码,那么这将不是问题,以便您以后可以执行某种清理步骤;但是,它的确给您带来了负担.

This won't be an issue if you write your code in such a way that it tracks adds so that you can later do some kind of cleanup step; however, it does put the onus on you.

现在,如果所有浏览器都支持getEventListeners,而Chrome这样做的话,情况可能就不同了.阅读,以了解为什么不希望这样做.

Now if all browsers supported getEventListeners as Chrome does this could be a different story. Read this for an understanding of why this is not desirable.

这篇关于jQuery off方法是否删除通过addEventListener添加的事件侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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