jQuery首先选择all

use*_*est 263 jquery jquery-selectors

在jQuery中,如何使用选择器访问除元素的第一个之外的所有元素?因此,在以下代码中,只能访问第二个和第三个元素.我知道我可以手动访问它们,但可能有任何数量的元素,所以这是不可能的.谢谢.

<div class='test'></div>
<div class='test'></div>
<div class='test'></div>
Run Code Online (Sandbox Code Playgroud)

kar*_*m79 560

$("div.test:not(:first)").hide();
Run Code Online (Sandbox Code Playgroud)

要么:

$("div.test:not(:eq(0))").hide();
Run Code Online (Sandbox Code Playgroud)

要么:

$("div.test").not(":eq(0)").hide();
Run Code Online (Sandbox Code Playgroud)

要么:

$("div.test:gt(0)").hide();
Run Code Online (Sandbox Code Playgroud)

或者:(根据@Jordan Lev的评论):

$("div.test").slice(1).hide();
Run Code Online (Sandbox Code Playgroud)

等等.

看到:

  • 这是一个比较所有这些解决方案的JsPerf:http://jsperf.com/fastest-way-to-select-all-expect-the-first-one根据项目的数量,`$("li"). (":eq(0)")`似乎很好. (19认同)
  • 喜欢这个清单.只想添加:`$("div.test:first").siblings().hide()`.发现从第一个元素开始对我有用,然后隐藏它的所有兄弟,即使它们没有找到共同的选择器. (4认同)
  • 棒极了!只是一个小评论; 我不认为gt是一个JQuery函数,至少在我使用的版本中没有.我得到一个TypeError:.gt不是一个函数. (2认同)

Gon*_*ing 29

由于jQuery选择器从右到左的方式进行评估li:not(:first),因此评估会降低可读性.

同样快速且易于阅读的解决方案是使用功能版本.not(":first"):

例如

$("li").not(":first").hide();
Run Code Online (Sandbox Code Playgroud)

JSPerf: http ://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6

这比只慢几个百分点slice(1),但是非常可读,因为"我想要除了第一个以外的所有".