返回介绍

:nth-last-child() Selector

发布于 2017-09-11 17:05:53 字数 3679 浏览 1171 评论 0 收藏 0

所属分类:选择器 > 子元素过滤

nth-last-child selector

描述: 选择所有他们父元素的第n个子元素。计数从最后一个元素开始到第一个。

  • 添加的版本: 1.9jQuery( ":nth-last-child(index/even/odd/equation)" )

    index: 每个相匹配子元素的索引值,从最后一个开始(1),也可以是字符串 evenodd,或一个方程式( 例如 :nth-last-child(even), :nth-last-child(4n) )

因为jQuery的实现:nth-child(n)是严格来自CSS规范,所以n值是“1索引”,也就是说,从1开始计数。对于所有其他选择器表达式,jQuery遵循JavaScript的“0索引”的计数。因此,给定一个单一<ul>包含两个<li>$('li:nth-child(1)')选择第一个<li>,而$('li:eq(1)')选择第二个。

这个不寻常的用法,可进一步讨论中找到W3C CSS specification.

例子:

Example: 在每个匹配的ul中查找倒数第二个li,并将它标记出来。

<!DOCTYPE html>
<html>
<head>
  <style>
  div { float:left; }
  span { color:blue; }
  </style>
  <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
  <div>
  <ul>
    <li>John</li>
    <li>Karl</li>
    <li>Adam</li>
  </ul>
</div>
<div>
  <ul>
    <li>Dan</li>
  </ul>
</div>
<div>
  <ul>
    <li>Dave</li>
    <li>Rick</li>
    <li>Timmy</li>
    <li>Gibson</li>
  </ul>
</div>
<script>$("ul li:nth-last-child(2)").append("<span> - 2nd to last!</span>");</script>
 
</body>
</html>

Example: This is a playground to see how the selector works with different strings.

<!DOCTYPE html>
<html>
<head>
  <style>
button { display:block; font-size:12px; width:100px; }
div { float:left; margin:10px; font-size:10px;
      border:1px solid black; }
span { color:blue; font-size:18px; }
#inner { color:red; }
td { width:50px; text-align:center; }
</style>
  <script src="http://cdn.bootcss.com/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
  <div>
  <button>:nth-last-child(even)</button>
  <button>:nth-last-child(odd)</button>
  <button>:nth-last-child(3n)</button>
  <button>:nth-last-child(2)</button>
</div>
<div>
  <button>:nth-last-child(3n+1)</button>
  <button>:nth-last-child(3n+2)</button>
</div>
 
<div>
  <table>
    <tr><td>John</td></tr>
    <tr><td>Karl</td></tr>
    <tr><td>Brandon</td></tr>
    <tr><td>Benjamin</td></tr>
  </table>
</div>
<div>
  <table>
    <tr><td>Sam</td></tr>
  </table>
</div>
<div>
  <table>
    <tr><td>Glen</td></tr>
    <tr><td>Tane</td></tr>
    <tr><td>Ralph</td></tr>
    <tr><td>David</td></tr>
    <tr><td>Mike</td></tr>
    <tr><td>Dan</td></tr>
  </table>
</div>
 
<span>tr<span id="inner"></span></span>
 
<script>
$("button").click(function () {
  var str = $(this).text();
  $("tr").css("background", "white");
  $("tr" + str).css("background", "#ff0000");
  $("#inner").text(str);
});
</script>
 
</body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文