[英]jQuery select all except first
在jQuery中,如何使用选择器访问除元素的第一个元素以外的所有元素? 因此,在下面的代码中,仅第二和第三个元素将被访问。 我知道我可以手动访问它们,但是可以有任意数量的元素,因此不可能。 谢谢。
<div class='test'></div>
<div class='test'></div>
<div class='test'></div>
$("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();
等等。
看到:
由于从右到左评估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)
慢几个百分点,但由于“除了第一个,我要全部”,因此可读性强。
我的回答集中在一个扩展案例,该案例来自顶部暴露的案例。
假设您有一组元素,除了第一个元素外,您要从中隐藏子元素。 举个例子:
<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
元素。 因此这将无济于事,因为它将隐藏除visible#1
之外的所有.child
元素:
$('.child:not(:first)').hide();
解决方案(在这种扩展情况下)将是:
$('.some-group').each(function(i,group){ $(group).find('.child:not(:first)').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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.