注意我知道我添加了 id 并将它们组合在一个选择器中,例如#myDiv1,#myDiv2"所以请不要提出这个建议,因为它与我的问题无关.
N.B. I'm aware that I add ids and combine these in a selector e.g. "#myDiv1,#myDiv2" so please refrain from suggesting this as it does not relate to my question.
有没有办法在一个 on() 声明中将下面的变量链接"在一起,可能是一个数组或其他东西?
Is there a way to 'chain' the vars below together in one on() declaration maybe as an array or something?
var myDiv1 = $('<div>Something here</div>');
var myDiv2 = $('<div>Something else here</div>');
myDiv1.on('click', function(){ doSomething();});
myDiv2.on('click', function(){ doSomething();});
我有一堆变量,我需要对鼠标事件进行一些广泛的跟踪,并且像上面的示例一样单独设置它们感觉很混乱.
I have a bunch of vars that I need to do some broad tracking of mouse events and it feels messy setting them up individually like the above example.
您可以将 DOM 元素数组传递给 jQuery 函数:
$([
myDiv1.get(0),
myDiv2.get(0)
]).on('click', function(){ doSomething();});
jsFiddle 演示
另一种可能的方法是使用 .add() 方法:
Another possible way is to use the .add() method:
myDiv1.add(myDiv2).on('click', function(){ doSomething();});
jsFiddle 演示
将它们放在一个数组中,遍历它们并附加相同的处理程序.我使用 ES5 forEach 制作了示例,但您可以随意使用简单的 for 循环或 $.each.
Put them in an array, loop through them and attach the same handler. I made the example with ES5 forEach, but feel free to use a simple for loop or $.each.
[cucc, gomb].forEach(function (el) {
el.on('click', handler);
});
jsFiddle 演示
如果它们有共同的祖先,则在它们上放置一个共同的类并使用事件委托.根据您的元素数量,这可能是性能方面的最佳解决方案,因为您只需将一个处理程序附加到共同祖先.
If they have a common ancestor, put a common class on them and use event delegation. Depending on the number of your elements, this could be the best solution performance-wise, because you only have to attach one handler to the common ancestor.
$('.ancestor').on('click', '.common', handler);
jsFiddle 演示
这篇关于vars 引用的多个元素的 jquery on('click') 处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
在 Angular 2/Typescript 中使用 IScrollUse IScroll in Angular 2 / Typescript(在 Angular 2/Typescript 中使用 IScroll)
Anime.js 在 Ionic 3 项目中不起作用anime.js not working in Ionic 3 project(Anime.js 在 Ionic 3 项目中不起作用)
Ionic 3 - 使用异步数据更新 ObservableIonic 3 - Update Observable with Asynchronous Data(Ionic 3 - 使用异步数据更新 Observable)
Angular 2:在本地 .json 文件中找不到文件Angular 2: file not found on local .json file(Angular 2:在本地 .json 文件中找不到文件)
在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指In Ionic 2, how do I create a custom directive that uses Ionic components?(在 Ionic 2 中,如何创建使用 Ionic 组件的自定义指令?)
将 ViewChild 用于动态元素 - Angular 2 &离子2Use ViewChild for dynamic elements - Angular 2 amp; ionic 2(将 ViewChild 用于动态元素 - Angular 2 amp;离子2)