jquery on(#39;click#39;) handler for multiple elements referenced by vars(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 演示
这篇关于vars 引用的多个元素的 jquery on('click') 处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:vars 引用的多个元素的 jquery on('click') 处理程序


基础教程推荐
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01