Opposite of jQuery's :eq()

2019-01-23 23:34发布

问题:

Does anyone know if there exist some kind of selector to select al the elements from a matched set but the one given by the indicated index. E.g.:

$("li").neq(2).size();

Supposing that there were 5 elements, the last statement would give you 4, and would contain all the <li> elements but the second one in the DOM.

回答1:

Use not:

$('li').not(':eq(2)');


回答2:

The other answers will work just fine, but as an alternative you could implement you own custom selector for neq

$.extend($.expr[":"], {  
    neq: function(elem, i, match) {  
        return i !== (match[3] - 0);
    }  
});  

And then you could do what you originally suggested.

$("li:neq(2)").size();

Although another post suggested using .length instead of .size, which will be better as its just a property and not an extra function call.

$("li:neq(2)").length;


回答3:

Alright, it's just

$("li:not(:eq(2))");


回答4:

I would use filter for such case,

$('li').filter(function (i, item) {
   return i != 2;
})


回答5:

In addition to the custom selector, you could also implement this as a jQuery plugin:

$.fn.neg = function (index) {
    return this.pushStack( this.not(':eq(' + index + ')') );
}