我想在我的站点中的每个ul
容器中addClass "green"
到第5个li.hr
。
$("ul li.hr").each(function() {
if ($(this).length = 5) {
$(this).addClass("green");
}
});
附言:如果可以只与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
发布于 2010-07-27 09:13:50
你可以在纯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不支持~
选择器。在其他所有东西上都工作得很好。
发布于 2010-07-25 20:19:52
var lis = $('ul li.hr');
if(lis.length >= 4) {
$(lis[4]).addClass('green');
}
应该能行得通。我已经在Firebug中测试过了。
:nth-child选择器不会像您期望的那样工作,因为它没有考虑类选择器。
发布于 2010-07-13 17:43:28
您需要在那里使用nth-child
:
$("ul li.hr:nth-child(5)").addClass('green');
https://stackoverflow.com/questions/3235900
复制相似问题