jQuery选择所有除第一个之外的元素

309

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

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

看这个答案 https://dev59.com/mlPTa4cB1Zd3GeqPmtKZ#18322370 - AuthorProxy
4个回答

630

21
这里有一个 JsPerf 比较所有这些解决方案:http://jsperf.com/fastest-way-to-select-all-expect-the-first-one根据项目数量,$("li").not(":eq(0)") 看起来不错。 - Damien
4
我喜欢这个列表。只想补充一点:$("div.test:first").siblings().hide()。对我来说,从第一个元素开始,隐藏所有其兄弟元素即使它们没有被普遍选择器找到也很有用。 - Levi
2
很好的列表!只是有一个小评论;我认为gt不再是JQuery函数了,至少在我使用的版本中不是。我得到了一个TypeError:.gt不是一个函数。 - Dre
1
在选择为空的情况下,$("div.test").slice(1).hide(); 看起来最容易处理... - Frank N
1
@SandyGifford 这难道不会包括不在测试类中的兄弟姐妹吗?而且会错过不是兄弟姐妹的测试类元素吗? - Bob Stein
显示剩余13条评论

37
因为jQuery选择器的评估方式是从右到左,所以易于阅读的代码li:not(:first)由于该评估而变慢。
使用函数版本.not(":first")是同样快速且易于阅读的解决方案:
例如:
$("li").not(":first").hide();

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

这种方法只比slice(1)稍微慢一点,但是非常易读,可以表达“我想要全部内容,除了第一个”。


1
这也是我的最爱,我觉得它非常清晰易读,意图明确。 - Dre

4

我的回答聚焦于从顶部导出的扩展案例。

假设您有一组元素,您想隐藏其中的子元素,除了第一个。例如:

<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>
  1. We want to hide all .child elements on every group. So this will not help because will hide all .child elements except visible#1:

    $('.child:not(:first)').hide();
    
  2. The solution (in this extended case) will be:

    $('.some-group').each(function(i,group){
        $(group).find('.child:not(:first)').hide();
    });
    

1

$(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>


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