简体   繁体   English

如何删除使用纯JS在jQuery中设置的事件侦听器?

[英]how to remove event listener, set in jQuery, using pure JS?

I have a situation where a click eventlistener is being set on on a dynamic element using jQuery's .on: 我有一种情况是使用jQuery的.on在动态元素上设置了单击事件监听器:

$('body').on('click', '#email-me', function() {
    call my code....
});

and later on in the page, I have to remove this listener - but - and here's the catch - I DON'T have access to jQuery anymore (long story), which means pure js... 然后在页面的后面,我必须删除此侦听器-但是-这是要抓的-我不再可以使用jQuery(长话短说),这意味着纯js ...

so, I can't use unBind() , and even if i name my anonymous function up there, it still won't remove the event listener. 因此,我不能使用unBind() ,即使我在那里命名我的匿名函数,它也不会删除事件监听器。

How do I remove the bind, so this element isn't clickable anymore? 如何删除绑定,因此该元素不再可单击?

Thanks for reading! 谢谢阅读!

You can't. 你不能 jQuery events are handled differently than normal javascript events. jQuery事件的处理方式与普通javascript事件的处理方式不同。

When you add an event to an element with jQuery, these steps are followed: 当您使用jQuery将事件添加到元素时,请遵循以下步骤:

  1. If the element hasn't been initialized with an internal (internal to jquery) datacache, it gets initialized with a datacache, then the datacache is returned. 如果未使用内部(jQuery内部)数据缓存初始化该元素,则使用数据缓存对其进行初始化,然后返回该数据缓存。
  2. If this is the first event handler added for that event type, a special event is added to the element for that event type that executes jQuery.event.dispatch . 如果这是为该事件类型添加的第一个事件处理程序,则会向该事件类型的元素中添加一个特殊事件 ,该事件将执行jQuery.event.dispatch
  3. Finally, the handler(s) that you passed in are added to the datacache. 最后,您传入的处理程序将添加到数据缓存中。

Therefore, the only way for you to remove this event is to get ahold of the special event handler that jQuery bound that triggers jQuery.event.dispatch , but since you don't have access to jQuery, there's no way you will get that event handler. 因此,删除此事件的唯一方法是获取jQuery绑定的触发jQuery.event.dispatch特殊事件处理程序,但是由于您无权访问jQuery,因此无法获取该事件处理程序。 (even with access to jQuery, I don't think you can get that handler.) (即使可以访问jQuery,我也认为您无法获得该处理程序。)

You need to instead find a way to retain access to jQuery, or don't use it at all. 您需要找到一种保留对jQuery的访问的方法,或者根本不使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM