Simply put: the jQuery object is a composite pattern. How do I add jQuery objects to it?
简单地说:jQuery对象是一个复合模式。如何添加jQuery对象?
An example:
var e1 = $('#element1');
var e2 = $('#element2');
...
I know want to create a new jQuery object jq such that it is composed of e1 and e2. I want to be able to do something like the following:
我知道想创建一个新的jQuery对象jq,它由e1和e2组成。我希望能够做类似以下的事情:
var jq = $();
jq.addInjQueryObjects([e1, e2]);
jq.hide();
how do I do this?
我该怎么做呢?
By the way, I realize that I could have just selected #element1 AND #element2 to begin with, that's not what I'm talking about.
顺便说一句,我意识到我可以选择#element1 AND#element2开始,这不是我所说的。
1 个解决方案
#1
7
You can use jQuery's .add()
method:
你可以使用jQuery的.add()方法:
var e1 = $('#element1');
var e2 = $('#element2');
var jq = $();
jq = jq.add(e1).add(e2);
jq.hide();
It returns a new jQuery object instead of modifying the original, so you need to overwrite the original if you want to reuse the same variable.
它返回一个新的jQuery对象而不是修改原始对象,因此如果要重用同一个变量,则需要覆盖原始对象。
EDIT: Note that you can also use jQuery.merge()
, which will modify the original, but you'll need to pass in an Array of the DOM elements instead of the jQuery objects.
编辑:请注意,您也可以使用jQuery.merge(),它将修改原始,但您需要传入DOM元素的数组而不是jQuery对象。
var e1 = $('#element1');
var e2 = $('#element2');
var jq = $();
$.merge( jq, [e1[0], e2[0]] );
jq.hide();
#1
7
You can use jQuery's .add()
method:
你可以使用jQuery的.add()方法:
var e1 = $('#element1');
var e2 = $('#element2');
var jq = $();
jq = jq.add(e1).add(e2);
jq.hide();
It returns a new jQuery object instead of modifying the original, so you need to overwrite the original if you want to reuse the same variable.
它返回一个新的jQuery对象而不是修改原始对象,因此如果要重用同一个变量,则需要覆盖原始对象。
EDIT: Note that you can also use jQuery.merge()
, which will modify the original, but you'll need to pass in an Array of the DOM elements instead of the jQuery objects.
编辑:请注意,您也可以使用jQuery.merge(),它将修改原始,但您需要传入DOM元素的数组而不是jQuery对象。
var e1 = $('#element1');
var e2 = $('#element2');
var jq = $();
$.merge( jq, [e1[0], e2[0]] );
jq.hide();