[英]jquery on('click') handler for multiple elements referenced by vars
NB I'm aware that I add ids and combine these in a selector eg "#myDiv1,#myDiv2" so please refrain from suggesting this as it does not relate to my question.注意我知道我添加了 id 并将它们组合在一个选择器中,例如“#myDiv1,#myDiv2”,所以请不要提出这个建议,因为它与我的问题无关。
Is there a way to 'chain' the vars below together in one on() declaration maybe as an array or something?有没有办法在一个 on() 声明中将下面的变量“链接”在一起,可能作为数组或其他东西?
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.我有一堆 vars,我需要对鼠标事件进行一些广泛的跟踪,并且像上面的例子一样单独设置它们感觉很乱。
You can pass an array of DOM elements to the jQuery function : 您可以将DOM元素数组传递给jQuery函数 :
$([ myDiv1.get(0), myDiv2.get(0) ]).on('click', function(){ doSomething();});
Another possible way is to use the .add()
method : 另一种可能的方法是使用
.add()
方法 :
myDiv1.add(myDiv2).on('click', function(){ doSomething();});
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
. 我使用ES5
forEach
进行了示例,但可以随时使用简单的for
循环或$.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);
Adding to Kapa's answer.添加到卡帕的答案。 If you need to bind multiple elements to which have been added, prepended, appended, loaded with ajax or javascript.
如果您需要绑定已添加、前置、附加、加载的多个元素,请使用 ajax 或 javascript。
Loop through multiple classes and create bindings "for each" element遍历多个类并为“每个”元素创建绑定
var thisButton = '.this-button', //This element was added by js
thatButton = '.that-button', //That element was added by ajax
thesebuttons = [thisButton, thatButton];
thesebuttons.forEach(function (button) {
$(document).on('click touchend', button, function (e) {
// 'e' or event, uncomment to prevent button's default event
// e.preventDefault();
// Now do your function stuff
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.