Select multiple jQuery objects with .add()

前端 未结 3 1458
慢半拍i
慢半拍i 2020-12-03 10:16

Does the .add() method allow selecting multiple objects in one go instead of adding one at a time?

one.add(two).add(three).add(four).on(\"click\", function()         


        
相关标签:
3条回答
  • 2020-12-03 10:27

    I'd prefer this array approach, purely for readability...

    $([one, two, three, four]).each(function() {
        // your function here
    });
    
    0 讨论(0)
  • 2020-12-03 10:35

    You cannot add multiple objects in one go, for example:

    var groupThree = one.add(three, five); // will not work as expected
    

    You could cache the added objects so that you only have to do the add one time - 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'});
    });
    

    But I like the array method better, this is just a different way of thinking about it.

    0 讨论(0)
  • 2020-12-03 10:37

    You could put them into an array like this

    var k = [one,two,three,four]
    
    $.each(k,function(){
      $(this).click(function(){
         //Function here
       });
    });
    
    0 讨论(0)
提交回复
热议问题