简体   繁体   中英

jQuery - Join jQuery Objects, equivalent to Multiple Selector

I have this:

$(window).load(function(){
   var var1 = $('selector1').find('iframe').contents().find('body').find('selector2')
   var var2 = $('selector3');
   // Some function
   }); //end

I can do this: (somefunction() doesn't exists as a function, it could be any function)

$(var1).somefunction(someattributes);
$(var2).somefunction(someattributes);

But I want to do something like this: (jointhisselectorwith() doesn't exists as a function, it's what I want)

$(var1).jointhisselectorwith(var2).somefunction(someattributes);

It's possible to join jQuery objects? Thanks!

You can use add .

If var1 and var2 contain selectors:

$(var1).add(var2).somefunction(someattributes);

Or it also works with jQuery instances (which is what you have, you didn't need the $(var1) bit at all):

var j1 = $(var1);
var j2 = $(var2);
j1.add(j2).somefunction(someattributes);

Gratuitous live example:

 setTimeout(function() { var var1 = ".foo"; var var2 = ".bar"; $(var1).add(var2).css("color", "green"); setTimeout(function() { var j1 = $(".foo"); var j2 = $(".bar"); j1.add(j2).css("color", "blue"); }, 500); }, 500); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <div class="foo">I'm foo</div> <div class="bar">I'm bar</div> <div class="foo">I'm foo</div> <div class="bar">I'm bar</div> <div class="foo">I'm foo</div> <div class="bar">I'm bar</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM