jQuery事件触发所有侦听器

时间:2021-12-07 00:02:05

I have a custom event I've made which I would like to trigger at some point with no relevance to selection.

我有一个我自己制作的自定义事件,我希望在某些时候触发,与选择无关。

I.E - I would like to do something that would behave as running

I.E - 我想做一些表现得像跑步的事情

$("*").trigger('customEvent');

But jQuery documentation warns that using the universal selector is very slow. Is there a way to trigger all the object that are bound to a specific event without having to use the universal selector $("*")?

但是jQuery文档警告说使用通用选择器非常慢。有没有办法触发绑定到特定事件的所有对象而不必使用通用选择器$(“*”)?

Thanks!

P.S - I'm currently using a specific class called custom_event_listener and use $('.custom_event_listener').trigger('customEvent') to avoid using a universal selector. I'm wondering if there is a way to avoid the use of a class.

P.S - 我目前正在使用一个名为custom_event_listener的特定类,并使用$('。custom_event_listener')。trigger('customEvent')来避免使用通用选择器。我想知道是否有办法避免使用课程。

1 个解决方案

#1


15  

You can trigger an event on everything that has a handler bound like this:

您可以在具有如下处理程序绑定的所有内容上触发事件:

$.event.trigger('customEvent'); 

This loops through $.cache to find what actually has a handler, then fires on those elements...rather than just finding every element and firing the event on each one.

这循环通过$ .cache来查找实际拥有处理程序的内容,然后触发这些元素......而不是仅查找每个元素并在每个元素上触发事件。

#1


15  

You can trigger an event on everything that has a handler bound like this:

您可以在具有如下处理程序绑定的所有内容上触发事件:

$.event.trigger('customEvent'); 

This loops through $.cache to find what actually has a handler, then fires on those elements...rather than just finding every element and firing the event on each one.

这循环通过$ .cache来查找实际拥有处理程序的内容,然后触发这些元素......而不是仅查找每个元素并在每个元素上触发事件。