Javascript 与 jQuery 的 :eq() 相反
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12057251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Opposite of jQuery's :eq()
提问by manutenfruits
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.
假设有 5 个元素,最后一条语句将为您提供 4 个元素,并且将包含<li>
DOM 中除第二个元素之外的所有元素。
回答by manutenfruits
Alright, it's just
好吧,这只是
$("li:not(:eq(2))");
回答by James Wiseman
The other answers will work just fine, but as an alternative you could implement you own custom selector for neq
其他答案将工作得很好,但作为替代方案,您可以实现自己的自定义选择器 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.
虽然另一篇文章建议使用.length
而不是.size
,这会更好,因为它只是一个属性而不是额外的函数调用。
$("li:neq(2)").length;
回答by Selvakumar Arumugam
I would use filter for such case,
我会在这种情况下使用过滤器,
$('li').filter(function (i, item) {
return i != 2;
})
回答by Eli
In addition to the custom selector, you could also implement this as a jQuery plugin:
除了自定义选择器,您还可以将其实现为 jQuery 插件:
$.fn.neg = function (index) {
return this.pushStack( this.not(':eq(' + index + ')') );
}