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

<div class='test'></div>
<div class='test'></div>
<div class='test'></div>

$("div.test:not(:first)").hide();

or:

$("div.test:not(:eq(0))").hide();

or:

$("div.test").not(":eq(0)").hide();

or:

$("div.test:gt(0)").hide();

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

$("div.test").slice(1).hide();

等等。

See:

http://api.jquery.com/first-selector/ http://api.jquery.com/not-selector/ http://api.jquery.com/gt-selector/ https://api.jquery.com/slice/

因为jQuery选择器的计算方式是从右向左的,所以可读性很好的li:not(:first)会因为计算而变慢。

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

e.g.

$("li").not(":first").hide();

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

这只比slice(1)慢了几个百分点,但是可读性很好,因为“除了第一个,我想要所有的”。

我的回答集中在一个扩展的情况下,从一个暴露在上面。

假设您有一组元素,希望隐藏其中的子元素。举个例子:

<html>
  <div class='some-group'>
     <div class='child child-0'>visible#1</div>
     <div class='child child-1'>xx</div>
     <div class='child child-2'>yy</div>
  </div>
  <div class='some-group'>
     <div class='child child-0'>visible#2</div>
     <div class='child child-1'>aa</div>
     <div class='child child-2'>bb</div>
  </div>
</html>

我们想要隐藏每个组上的所有。child元素。所以这不会有帮助,因为它会隐藏所有的。child元素,除了visible#1: $ (' .child:不(首先)')hide (); 解决方案(在这个扩展的情况下)将是: $ (' .some-group ') . each(函数(i组){ 美元(集团);(.child:不(:第一))hide (); });

$(document).ready(function(){ $(".btn1").click(function(){ $("div.test:not(:first)").hide(); }); $(".btn2").click(function(){ $("div.test").show(); $("div.test:not(:first):not(:last)").hide(); }); $(".btn3").click(function(){ $("div.test").hide(); $("div.test:not(:first):not(:last)").show(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class="btn1">Hide All except First</button> <button class="btn2">Hide All except First & Last</button> <button class="btn3">Hide First & Last</button> <br/> <div class='test'>First</div> <div class='test'>Second</div> <div class='test'>Third</div> <div class='test'>Last</div>