简体   繁体   English

jQuery - 加入jQuery Objects,相当于Multiple Selector

[英]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) 我可以这样做:( somefunction()不作为函数存在,它可以是任何函数)

$(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) 但是我想做这样的事情:( jointhisselectorwith()不作为函数存在,它就是我想要的)

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

It's possible to join jQuery objects? 可以加入jQuery对象吗? Thanks! 谢谢!

You can use add . 你可以使用add

If var1 and var2 contain selectors: 如果var1var2包含选择器:

$(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): 或者它也适用于jQuery实例(这是你拥有的,你根本不需要$(var1)位):

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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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