如何使用多个 jquery 对象变量作为选择器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18504075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:48:42  来源:igfitidea点击:

How to use multiple jquery object variables as selectors?

jqueryjquery-selectors

提问by ingredient_15939

In jQuery, selecting more than one element can be done like this:

在 jQuery 中,可以像这样选择多个元素:

$("#id1,#id2").show();

But when I have two jQuery objects, I don't seem to be able to select more than one using the variables themselves. For example:

但是当我有两个 jQuery 对象时,我似乎无法使用变量本身选择多个。例如:

var jqId1 = $("#id1");
var jqId2 = $("#id2");
$(jqId1).show();       // This works.
$(jqId1,jqId2).show(); // This only shows jqId1.

See jsFiddle: http://jsfiddle.net/jr9Q2/

参见 jsFiddle:http: //jsfiddle.net/jr9Q2/

Is there another way of specifying multiple jq variables as selectors?

是否有另一种方式将多个 jq 变量指定为选择器?

回答by Denys Séguret

You can use add:

您可以使用添加

jqId1.add(jqId2).show();

But don't make your code too complex just to avoid querying "#id1,#id2": this selector relies on getElementByIdand is very fast.

但是不要为了避免查询而让你的代码太复杂"#id1,#id2":这个选择器依赖getElementById并且非常快。

回答by Gytis Vinclovas

You can use each cycle:

您可以使用每个循环:

$([jqId1, jqId2]).each( function(){
    $(this).show();
});

As answered here: Select multiple jQuery objects with .add()

如此处所回答: 使用 .add() 选择多个 jQuery 对象