由vars引用的多个元素的jquery on('click')处理程序 [英] jquery on('click') handler for multiple elements referenced by vars
问题描述
N.B。我知道我添加了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();});
我有一堆vars,我需要做一些广泛的鼠标事件跟踪,感觉很乱如上面的例子那样单独设置它们。
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();});
另一个可能的方法是使用
.add()
方法:Another possible way is to use the
.add()
method:myDiv1.add(myDiv2).on('click', function(){ doSomething();});
将它们放在数组中,循环使用并附加相同的处理程序。我使用ES5 forEach 做了一个例子,但是可以使用一个简单的
来获取
循环或$ .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 simplefor
loop or$.each
.[cucc, gomb].forEach(function (el) { el.on('click', handler); });
如果他们有一个共同的祖先,在他们上面放一个共同的类,并使用事件委托。根据您的元素数量,这可能是性能最好的解决方案,因为您只需将一个处理程序附加到共同的祖先。
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);
这篇关于由vars引用的多个元素的jquery on('click')处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!