vars 引用的多个元素的 jquery on('click') 处理程序
注意我知道我添加了 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 simplefor
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 演示
相关文章