我想在我网站的每个addClass "green"
个容器中li.hr
到第5个ul
。
$("ul li.hr").each(function() {
if ($(this).length = 5) {
$(this).addClass("green");
}
});
PS:如果只能使用CSS,请告诉我如何。
请注意ul
包含混合元素,例如:
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">foo</li>
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
我需要第5个li.hr
。
答案 0 :(得分:16)
尽管有广泛的共识,但您不能在此使用:nth-child
,因为它会计算所有子项,无论它们是否与前面的选择器匹配。只有在之后它抓取第n个元素才会将它与选择器进行比较以确定它是否匹配。所以:ul li.hr:nth-child(5)
实际上被视为ul li:nth-child(5).hr
。这可能听起来很奇怪,但它严格符合CSS规范(参见jQuery description)。
幸运的是,jQuery提供了精彩的:eq()
伪类,允许您通过从零开始的索引进行过滤,和尊重前面的选择器......
$("ul > li.hr:eq(4)").addClass("green");
我甚至对此进行了测试以确保其有效...
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.green { color:green; font-weight:bold; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("ul > li.hr:eq(4)").addClass("green");
});
</script>
</head>
<body>
<ul>
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">foo</li>
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">foo</li>
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
<li class="a">foo</li>
<li class="b">foo</li>
<li class="hr">bar</li> <!-- 5th -->
<li class="c">foo</li>
<li class="a">foo</li>
<li class="hr">foo</li>
</ul>
</body>
</html>
答案 1 :(得分:15)
您可以使用jquery的nth-child。
$("ul li.hr:nth-child(5)").addClass("green");
答案 2 :(得分:7)
您可以在纯CSS中执行此操作:
/* set rule: select every li.hr element after the 4th */
ul > li.hr ~ li.hr ~ li.hr ~ li.hr ~ li.hr {
color: green;
}
/* unset rule: select every li.hr element after the 5th */
ul > li.hr ~ li.hr ~ li.hr ~ li.hr ~ li.hr ~ li.hr {
/* reverse the rules set in the previous block here */
color: black;
}
警告:IE6不支持~
选择器。在其他一切工作正常。
答案 3 :(得分:5)
$('ul').find('li.hr:nth-child(5)').each(function() {
$(this).addClass("green");
});
CSS3 提供类似的选择器,读取http://www.w3.org/TR/css3-selectors/#nth-child-pseudo
看起来像
li.hr:nth-child(5) {
background-color: green;
}
答案 4 :(得分:3)
答案 5 :(得分:1)
答案 6 :(得分:0)
你需要nth-child
:
$("ul li.hr:nth-child(5)").addClass('green');
答案 7 :(得分:-2)
你可以这样做。
if($("ul li.hr")[4]){
$($("ul li.hr")[4]).addClass("green");
}