使用.add()选择多个jQuery对象

Ant*_*ony 25 javascript jquery

.add()方法是否允许一次选择多个对象而不是一次添加一个?

one.add(two).add(three).add(four).on("click", function() { });
Run Code Online (Sandbox Code Playgroud)

以下变量以它们的方式设置,因为每个变量都具有不同的功能.

var one   = $("#1");
var two   = $("#2");
var three = $("#3");
var four  = $("#4");
Run Code Online (Sandbox Code Playgroud)

但是,如果我想添加一个适用于所有这些元素的额外函数呢?我是否必须逐个添加它们?

我知道你可以选择全部使用$("#1,#2,#3,#4"),但我只是想利用上面的变量.

Arc*_*her 32

我更喜欢这种阵列方法,纯粹是为了可读性......

$([one, two, three, four]).each(function() {
    // your function here
});
Run Code Online (Sandbox Code Playgroud)


Jay*_*ard 11

您不能一次添加多个对象,例如:

var groupThree = one.add(three, five); // will not work as expected
Run Code Online (Sandbox Code Playgroud)

你可以缓存添加的对象,这样你只需要添加一次 - http://jsfiddle.net/X5432/

var one   = $("#1");
var two   = $("#2");
var three = $("#3");
var four  = $("#4");
var five  = $("#5");

var groupOne = one.add(two).add(three).add(four);
var groupTwo = groupOne.add(five);

$('#first').click(function(e){
    e.preventDefault();
    groupOne.css({'background': '#00FF00'});
});

$('#second').click(function(e){
    e.preventDefault();
    groupTwo.css({'background': '#FF0000'});
});
Run Code Online (Sandbox Code Playgroud)

但我更喜欢数组方法,这只是一种不同的思考方式.

  • 这很好,你可以通过使用它来获得更多的好处:`groupOne.click(function(e){});` (2认同)

Ant*_*ton 5

您可以将它们放入这样的数组中

var k = [one,two,three,four]

$.each(k,function(){
  $(this).click(function(){
     //Function here
   });
});
Run Code Online (Sandbox Code Playgroud)

  • 或者就这样做:`$(k).click(function(){...})` (7认同)