• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • :nth-last-of-type(index/even/odd/equation)

    选择的所有他们的同级元素的第n个兄弟元素,计数从最后一个元素到第一个。

    jQuery(":nth-last-of-type(index/even/odd/equation)")

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

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

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

    例子

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

    <!DOCTYPE html>
    <html>
    <head>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
    
      <ul>
        <li>John</li>
        <li>Karl</li>
        <li>Adam</li>
      </ul>
    
      <ul>
        <li>Dan</li>
      </ul>
    
      <ul>
        <li>Dave</li>
        <li>Rick</li>
        <li>Timmy</li>
        <li>Gibson</li>
      </ul>
    
    <script>$("ul li:nth-last-of-type(2)").append("<mark> - 2nd to last!</mark>");</script>
     
    </body>
    </html>
    
    • John
    • Karl
    • Adam
    • Dan
    • Dave
    • Rick
    • Timmy
    • Gibson

    看看选择器如何处理不同的字符串

    <!DOCTYPE html>
    <html>
    <head>
      <style>
    button { display:block;width:100px; }
    table{ float:left; margin:10px;}
    span { color:blue; font-size:18px; }
    #inner { color:red; }
    td { width:50px; text-align:center; }
    </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <div>
      <button>:nth-last-of-type(even)</button>
      <button>:nth-last-of-type(odd)</button>
      <button>:nth-last-of-type(3n)</button>
      <button>:nth-last-of-type(2)</button>
    </div>
    <div>
      <button>:nth-last-of-type(3n+1)</button>
      <button>:nth-last-of-type(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>
    
    John
    Karl
    Brandon
    Benjamin
    Sam
    Glen
    Tane
    Ralph
    David
    Mike
    Dan
    tr