2

I am trying to pass multiple numbers for objects for a certain class. here a preview of the piece I am trying to work on

group: function(number) {
      for(var i=0;i<number.length;i++){
         groups=number[i];
    $('.group')[groups].remove();
     }
   }

I am trying to make it so its like

code.destroy.group(0,1,2);

What this will do will remove $('.group')[0] $('.group')[1] and $('.group')[2]

I have to be doing this wrong or else this would be working correctly. Can someone lead me on the right path here.

Thanks to Felix King for leading me to the right path:

All I had to do is use the arguments parameter

group: function() {
    for(var i=0;i<arguments.length;i++){
        $('.sceditor-group')[arguments[i]].remove();
    }
  }
4

2 回答 2

2

jQuery objects are array-like objects that contain raw DOM elements.

Therefore, $(...)[0] is a raw DOM element, not a jQuery object.

To get a jQuery object for a specific element, call .eq().


EDIT: You're also looking for the special arguments array-like object, which you can loop through to get all of the arguments passed to your function.

于 2013-07-10T14:23:21.253 回答
1

There's a problem with your logic, and that is that since you remove an element of the matching set on each iteration of your cycle, you won't remove the initial elements with index 0,1 & 2 (in that case you'd end up removing the elements 0, 2 & 4 of the original set) . Also you're calling $('.group') on each iteration which is not optimal, instead is better if you take advantage of caching the variable, and then add the element you need one by one, and then you can just call remove on the resulting set.

You could change your function to:

group: function(number) {
      var $current = $();
      var $group = $('.group');
      for(var i=0;i<number.length;i++){
         $current = $current.add($group.eq(number[i]));
      }
      $current.remove();
}

EDIT: Considering SLaks answer and the usage of arguments instead of expecting an array, you could do it like this:

group: function() {
      var $current = $();
      var $group = $('.group');
      for(var i=0;i<arguments.length;i++){
         $current = $current.add($group.eq(arguments[i]));
      }
      $current.remove();
}
于 2013-07-10T14:27:36.883 回答