jQuery选择器 – 除了第一个之外的所有选择

我有一个小的jQuery选择器问题,我有以下html:

我想隐藏(使用jQuery)所有持有“member-info”类的div,但不是那个拿着“第一”类的人,有什么想法吗?

 $('.member-info:not(.first)').hide(); 

这使用not-selector (docs)来排除first类的元素。

或者,如果first类的目的只是识别first类,那么请改为:

 $('.member-info').slice(1).hide(); 

这使用slice() (docs)方法返回以第二个匹配开头的集合。

 $(".member-info:not('.first')").hide(); $(".member-info").filter(":not('.first')").hide(); $('.member-info').not('.first').hide(); $(".member-info:not(:first)").hide(); $(".member-info").filter(":not(':first')").hide(); $('.member-info').not(':first').hide(); $(".member-info:not(:eq(0))").hide(); $(".member-info").filter(":not(':eq(0)')").hide(); $(".member-info").not(":eq(0)").hide(); $(".member-info:not(:lt(1))").hide(); $(".member-info").filter(":not(':lt(1)')").hide(); $(".member-info").not(":lt(1)").hide(); $(".member-info:gt(0)").hide(); $(".member-info").filter(':gt(0)').hide(); $(".member-info").slice(1).hide(); 

所有可能的方式都会浮现在我的脑海中。 我还进行了JavaScript性能比较 ,你可以找到一些不可思议的结果。

所有这些示例都适用于jQuery的v1.10。*。

大多数情况下,这一个是最快的$(".member-info").slice(1).hide(); 看起来像是相关的,而不是头脑风暴的答案

这不能完全回答您的问题,但您可以使用gt跳过第一个匹配的元素。

例如:

 $('div.member-info:gt(0)') 

请参阅: http : //api.jquery.com/gt-selector/

使用:not()选择器 。 例如:

 $(".member-info:not(first)").hide(); 

如果第一个真的总是第一个孩子,请尝试

 $(".member-info:not(member-info:first)").hide(); 

我也遇到过这个问题。 但是,我没有方便地创建一个名为first class的类来排除我的元素。 这是我在本例中使用的选择器的解决方案:

 $('.member-info:not(:first)');//grab all .member-info except the first match 

这应该工作:

 $('.member-info').not('.first').hide(); 

使用not()

如何$('.member-info').not('.first').hide();

@AuthorProxy@David Thomas @Maximilian Ehlers都建议$('.member-info').not('.first').hide(); 在他们的答案中,这是一个非常快速,非常易读的解决方案。

由于jQuery选择器从右到左的方式进行评估,因此该评估实际上减慢了可读性".member-info:not(.first)"

一个快速且易于阅读的解决方案确实使用函数版本.not(".first")或甚至只是.not(":first")

例如

 $(".member-info").not(".first").hide(); // Class selector 

要么

 $(".member-info").not(":first").hide(); // Positional selector 

相关选择器的JSPerf: http ://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

.not(':first')只比slice(1)慢几个百分点,但是非常可读,因为“我想要除了第一个以外的所有”。