How to use multiple jquery object variables as selectors?

馋奶兔 提交于 2019-12-17 10:58:34

问题


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

$("#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:

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

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

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


回答1:


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 getElementById and is very fast.




回答2:


You can use each cycle:

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

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



来源:https://stackoverflow.com/questions/18504075/how-to-use-multiple-jquery-object-variables-as-selectors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!