jQuery首先选择所有内容


272

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

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

Answers:


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

要么:

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

要么:

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

要么:

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

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

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

等等。

看到:


19
这是一个比较所有这些解决方案的JsPerfjsperf.com/fastest-way-to-select-all-expect-the-first-one 根据项目数量,这$("li").not(":eq(0)")似乎不错。
达米安

4
喜欢这个清单。只是想添加:$("div.test:first").siblings().hide()。发现从第一个元素开始对我很有用,然后隐藏所有同级兄弟,即使没有使用公共选择器找到它们也是如此。
Levi

2
很棒的清单!只是一点点评论;我认为gt不再是JQuery函数,至少在我使用的版本中不再如此。我收到TypeError:.gt不是函数。
德雷(Dre)

1
$("div.test").slice(1).hide();在选择空缺的情况下看起来最宽容...
Frank Nocke

1
@SandyGifford不会包括不在测试班级中的兄弟姐妹吗?错过不是兄弟姐妹的测试类元素吗?
鲍勃·斯坦

30

由于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)

3

我的回答集中在一个扩展案例,该案例来自顶部暴露的案例。

假设您有一组元素,除了第一个元素外,您要从中隐藏子元素。举个例子:

<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. 我们要隐藏.child每个组中的所有元素。因此,这将无济于事,因为它将隐藏所有.child元素,除了visible#1

    $('.child:not(:first)').hide();
  2. 解决方案(在这种扩展情况下)将是:

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.