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 simpleforloop 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') 处理程序
基础教程推荐
- 在 contenteditable 中精确拖放 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- 如何添加到目前为止的天数? 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- Bokeh Div文本对齐 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
