简体   繁体   English

如何在每个UL中仅选择第4个或更高的LI?

[英]How do I select only the 4th and higher LIs in each UL?

For this XHTML: 对于此XHTML:

<ul class="collapse">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>

<ul class="collapse">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>

Using jQuery, how do I select only the 4th and higher LIs in each UL? 使用jQuery,如何在每个UL中仅选择第4个和更高的LI?

I've tried: 我试过了:

$("ul.collapse li:gt(2)").css("color", "red");

But it selects the 4th and higher LIs in the whole document. 但是它会在整个文档中选择第4个或更高的LI。 "Four", "Five", and "1", "2", "3", "4" are red. “四个”,“五个”和“ 1”,“ 2”,“ 3”,“ 4”为红色。

You can do it like this: 您可以这样做:

$("ul.collapse").find("li:gt(2)").css("color", "red");

You can play with/test it here . 您可以在此处进行测试 This finds each <ul class="collapse"> then for each one independently evaluates the find selector, giving you the result you're after. 这将查找每个 <ul class="collapse">然后针对 每个 <ul class="collapse"> 独立评估查找选择器,从而为您提供所要的结果。

Nth-child will do the trick as well. 第N个孩子也可以做到。

$(document).ready(function(){
    $('.collapse li:nth-child(n+4)').css("color", "red");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM