在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();
等等 .
看到:
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) .
li:not(:first)
同样快速且易于阅读的解决方案是使用函数版本 .not(":first") :
.not(":first")
例如
$("li").not(":first").hide();
JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
这比 slice(1) 慢了几个百分点,但是"I want all except the first one"非常易读 .
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: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> <div class='test'>First</div> <div class='test'>Second</div> <div class='test'>Third</div> <div class='test'>Last</div>
4 回答
要么:
要么:
要么:
或者:(根据@Jordan Lev的评论):
等等 .
看到:
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")
:例如
JSPerf: http://jsperf.com/fastest-way-to-select-all-expect-the-first-one/6
这比
slice(1)
慢了几个百分点,但是"I want all except the first one"非常易读 .我的答案集中在一个扩展的案例中,该案例源自顶部暴露的案例 .
假设您有一组要从中隐藏子元素的元素,除了第一个元素 . 举个例子:
.child
元素 . 所以这无济于事,因为除了visible#1
之外会隐藏所有.child
元素: