jQuery :nth-last-child() 選擇器



:nth-last-child() 選擇器用於根據元素在其兄弟元素中的位置選擇一個或多個元素,計數從末尾開始。

此選擇器採用特定數字、關鍵字(even 或 odd)或公式 (an + b) 來根據元素的位置進行匹配。

與從開頭計數的:nth-child() 選擇器不同,:nth-last-child() 從最後一個子元素向第一個子元素計數。

語法

以下是 jQuery :nth-last-child() 選擇器的語法:

:nth-last-child(n|even|odd|formula)

引數

以下是上述語法的描述:

  • n: 選擇其父元素的第 n 個子元素。索引從 1 開始,而不是 0。
  • even|odd: 分別選擇偶數和奇數編號的子元素。
  • formula: 根據數學公式 (an+b) 選擇元素。“a”和“b”是整數。

示例 1

在下面的示例中,我們使用“jQuery :nth-last-child()”選擇器來選擇其父元素(<ul>)的第 2 個<li>子元素,計數從最後一個子元素開始:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $("li:nth-last-child(2)").css("background-color", "yellow");
        });
        </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
    </ul>
</body>
</html>

執行上述程式後,倒數第二個<li>元素的背景顏色將變為黃色。

示例 2

在這個示例中,我們使用“odd”和“even”引數來選擇奇數和偶數子元素(<li>),計數從最後一個子元素開始:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $("li:nth-last-child(odd)").css("background-color", "yellow");
          $("li:nth-last-child(even)").css("background-color", "lightblue");  
        });
    </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
        <li>Item 6</li>
    </ul>
</body>
</html>

執行程式後,從最後一個子元素開始計數,奇數編號的列表項將以黃色突出顯示,偶數編號的列表項將以淺藍色突出顯示。

示例 3

p:nth-last-child(3n+1) 選擇<div>元素中從最後一個子元素開始計數的每個第一個和後續的第三個段落:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
          $("p:nth-last-child(3n+1)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
<div>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
    <p>Paragraph 5</p>
    <p>Paragraph 6</p>
    <p>Paragraph 7</p>
    <p>Paragraph 8</p>
</div>
</body>
</html>

執行上述程式後,選定的元素將以黃色突出顯示。

jquery_ref_selectors.htm
廣告
© . All rights reserved.