简体   繁体   English

如何将多个jQuery对象收集到一个jQuery对象中?

[英]How do I gather multiple jQuery objects into one jQuery object?

Say I have these variables: 说我有这些变量:

var container = $("div#my-awesome-section");
var foo_input = $("input[name=foo]", container);
var bar_input = $("input[name=bar]", container);

I want to bind an event handler to both inputs. 我想将事件处理程序绑定到两个输入。 I hoped this would work: 我希望这会起作用:

$([foo_input, bar_input]).on("keypress", function() { /* ... */ });

But alas, no. 但是a,不。 Is there a convenient way of gathering multiple jQuery objects into one for purposes like this? 是否有一种方便的方法可以将多个jQuery对象收集到一个这样的目的?

在jquery的add()中使用以添加 adding jquery object

foo_input.add(bar_input).on("keypress", function() { /* ... */ });

Solution 1: 解决方案1:

for using with object, you need to use .add() 与对象一起使用时,需要使用.add()

Create a new jQuery object with elements added to the set of matched elements. 创建一个新的jQuery对象,将元素添加到匹配的元素集中。

 foo_input.add(bar_input).on("keypress", function() { /* ... */ });

Solution 2: 解决方案2:

also you can simply use comma separated multiple selector: 您也可以简单地使用逗号分隔的多个选择器:

 $("input[name=foo],input[name=bar]", container).on("keypress", function() { /* ... */ });

You can also try this: 您也可以尝试以下操作:

$.each([foo_input, bar_input], function() {
    /* ... */
});

See JSFiddle . 参见JSFiddle

In your case use: 在您的情况下使用:

$.each([foo_input, bar_input], function() {
    $(this).on("keypress", function() {
        /* ... */
    }); 
});

Reading the docs for jQuery's add() function, I noticed that my original attempt was almost correct. 在阅读jQuery的add()函数的文档时,我注意到我最初的尝试几乎是正确的。 It is possible to initialize a jQuery object with an array of DOM Elements, so I could do this: 可以使用DOM Elements数组初始化jQuery对象,所以我可以这样做:

$([foo_input[0], bar_input[0]]).on("keypress", ...

I highly prefer the add() function though. 我非常喜欢add()函数。

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

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