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

9

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

<div class="member-info first"></div>
<div class="member-info"></div>
<div class="member-info"></div>

我想使用jQuery隐藏所有包含“member-info”类的div,但不包括包含“first”类的div,你有什么想法吗?

1
可能是 jQuery选择除第一个外的所有元素 的重复问题。 - bwright
重复问题,参考 all-elements-but-the-firstall-elements-not-in-a-class。无论哪种方式,这个问题都特别混淆了将第一个元素的类命名为“first”。因此答案包括 ':not(:first)'':not(.first)' 甚至 ':not(first)' - Bob Stein
8个回答

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

这里使用了not-selector(文档)来排除具有first类的元素。

或者如果first类的作用只是为了标识第一个,那么可以改为:

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

这里使用了slice()(文档)方法,用于返回从第二个匹配项开始的一组结果。


1
+1 slice() 会更快,因为它只是从数组中删除一个元素,而不是让 jQuery 再次检查每个元素的类。 - Keltex
@Keltex:我同意。只要first类始终在集合中的第一个匹配项上,那么使用切片就是正确的方法。 - user113716
@Keltex 是的,但应该选择更清晰易懂的方式,因为类选择不太可能产生任何明显的影响。(与性能相关时,请在之前和之后进行分析) - cobbal

3

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

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

如果first始终是第一个子元素,可以尝试使用以下代码:
$(".member-info:not(member-info:first)").hide();

3
$(".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();,看起来相对应,不是脑力激荡的答案。

2
这并不完全回答了你的问题,但是你可以使用gt跳过第一个匹配元素。
例如:
$('div.member-info:gt(0)')

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

谢谢@Jon- 这个对我帮助很大。不确定为什么其他的没有用。 - Hairgami_Master

1

我也遇到了这个问题。然而,我没有方便地使用一个名为first的类来标记我的元素以进行排除。以下是我在此示例上下文中使用的选择器解决方案:

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

0

这应该可以工作:

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

使用not()函数。


0

这样怎么样:$('.member-info').not('.first').hide();


0

@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) 只慢了几个百分点,但可读性非常好,表达的意思是“我想要除第一个之外的所有项目”。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接