Combine jquery variables into one selector?

扶醉桌前 提交于 2020-06-23 05:34:49

问题


I'm looking for a way to combine jquery variables. Looking through related questions, nobody seems to be trying what I want to do.

$("body, div, p") is one method of combining by selectors, but after you assign a selector to a variable, how do you combine them in a similar fashion?

Here is one method I tried, but did not get it to work. I also tried putting them into an array (by simply adding brackets before $body and after $p).

$body = $("body");
$div = $("div");
$p = $("p");
$mixed = $($body, $div, $p);
// $mixed = $("body, div, p"); is NOT what I am looking for

In my actual script I've got some <select> inputs assigned to variables. I would like to put them into groups, so say I have a <select> which has "FRUIT" and another one that has "VEGETABLES", I could put them both into a jquery variable called "PRODUCE". Then if I need to perform anything on both of the two, I use produce instead.

...This might just be a stupid way to do things, though.


回答1:


Perhaps you're looking for .add()?

$mixed = $body.add($div).add($p);



回答2:


For me, it works fine in jQuery 1.10.2 to simply combine the elements in an array literal before passing into the jQuery constructor: $mixed = $([$body, $div, $p]);




回答3:


I too was looking for something like this. In my case I had some objects passed into a common function and some created in memory and I wanted to apply the same click event to all of the objects. In the end I went with James's add solution above but thought I would share another option.

If you put the objects into an array you can use the each iterator to perform an action on them.

[$body, $div, $p].each(function(i,e) { e.DoSomething(); });

This syntax is longer and you don't get a reusable $mixed object, but there may be some scenarios where this is useful.



来源:https://stackoverflow.com/questions/9056648/combine-jquery-variables-into-one-selector

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