在列表中找到具有指定类的第5个元素,并在jQuery中添加另一个类

Rép*_*pás 16 html css jquery html-lists

我想在我网站的每个容器中排在addClass "green"第5 位.li.hrul

$("ul li.hr").each(function() {
  if ($(this).length = 5) {
    $(this).addClass("green");
  }
});
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我需要第5名li.hr.

Jos*_*ola 16

尽管有普遍的共识,但你不能:nth-child在这里使用,因为它会计算所有孩子,无论他们是否与前面的选择器匹配.只有它抓取第n个元素之后才会将它与选择器进行比较以确定它是否匹配.所以这个:ul li.hr:nth-child(5)实际上被视为ul li:nth-child(5).hr.这可能听起来很奇怪,但它严格符合CSS规范(参见jQuery描述).

幸运的是,jQuery提供了很棒的:eq()伪类,允许你通过从零开始的索引进行过滤,尊重前面的选择器......

$("ul > li.hr:eq(4)").addClass("green");
Run Code Online (Sandbox Code Playgroud)

我甚至对此进行了测试以确保其有效...

<!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>
Run Code Online (Sandbox Code Playgroud)


Kru*_*nal 15

你可以使用jquery的nth-child.

$("ul li.hr:nth-child(5)").addClass("green");
Run Code Online (Sandbox Code Playgroud)


Bor*_*gar 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;
}
Run Code Online (Sandbox Code Playgroud)

警告:~IE6不支持选择器.在其他一切工作正常.

  • 每次我认为我都知道CSS我会看到这样的答案. (2认同)

jAn*_*ndy 5

$('ul').find('li.hr:nth-child(5)').each(function() {
   $(this).addClass("green");
});
Run Code Online (Sandbox Code Playgroud)

参考:: nth-child选择器

CSS3提供了类似的选择器,阅读http://www.w3.org/TR/css3-selectors/#nth-child-pseudo

看起来像

li.hr:nth-child(5) {
   background-color: green;
}
Run Code Online (Sandbox Code Playgroud)