How to add jQuery objects to the jQuery composite object
Simply put: the jQuery object is a composite pattern. How do I add jQuery objects to it?
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:
var jq = $();
jq.addIn开发者_如何学CjQueryObjects([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.
You can use jQuery's .add()
method:
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.
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.
var e1 = $('#element1');
var e2 = $('#element2');
var jq = $();
$.merge( jq, [e1[0], e2[0]] );
jq.hide();
精彩评论