简体   繁体   English

同时将事件绑定到多个jquery元素

[英]Bind event to multiple jquery elements simultaneously

I need to bind the same event (for example click ) to n jquery elements. 我需要将同一事件(例如click )绑定到n个 jquery元素。 I know I can achieve this result easily with a selector: 我知道我可以使用选择器轻松实现此结果:

$("#first, #second, .third").on("click", function(){});

but what if, instead of a selector, I want to use a list of jquery elements? 但是如果我要使用一个jquery元素列表而不是选择器怎么办?

This is the solution I'm using right now, assume you get $first and $second as a result of a function: 这是我现在正在使用的解决方案,假设您通过函数获得$first$second

var $first = $("#first");
var $second = $("#second");

$([$first[0], $second[0]]).on("click", function(){
    alert("click " + this.innerText)
});

find fiddle to play with here: https://jsfiddle.net/0z2r55d6/ 在这里找到小提琴玩耍: https : //jsfiddle.net/0z2r55d6/

as you can see I need to extract, for each jquery element, the HTML element and push it into an array. 如您所见,我需要为每个jquery元素提取HTML元素并将其推入数组。 I find this pretty ugly and unhandy.. Is there a better way to achieve the same result? 我觉得这很丑陋而且不方便。是否有更好的方法来达到相同的结果? I didn't find anything in jquery's documentation. 我在jquery的文档中找不到任何内容。

Thanks 谢谢

使用jQuery add()方法:

$first.add($second).add($third).on('click', handler);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM