jQuery :last-child 選擇器



jQuery 中的:last-child 選擇器用於選擇其父元素內的最後一個子元素。此選擇器通常用於對父元素的最後一個子元素應用樣式或執行操作。此選擇器適用於所有 HTML 元素。

如果我們想選擇其父元素的第一個子元素,我們需要使用:first-child 選擇器。

語法

以下是 jQuery 中 :last-child 選擇器的語法:

$(":last-child")

引數

:last-child 選擇指定父元素的最後一個子元素。

示例 1

在以下示例中,我們使用“:last-child”選擇器來選擇每個無序列表中的最後一個列表項:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("ul li:last-child").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>First item</li>
        <li>Second item</li>
        <li>Third item</li>
    </ul>
    <ul>
        <li>First item in second list</li>
        <li>Second item in second list</li>
    </ul>
</body>
</html>

執行上述程式後,每個無序列表中的最後一個列表項將以黃色背景突出顯示。

示例 2

在此示例中,我們選擇每個表格中的最後一行表格行:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("table tr:last-child").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <table border="1">
        <tr>
            <td>First row, first cell</td>
            <td>First row, second cell</td>
        </tr>
        <tr>
            <td>Second row, first cell</td>
            <td>Second row, second cell</td>
        </tr>
    </table>
    <br><br>
    <table border="1">
        <tr>
            <td>First row, first cell in second table</td>
            <td>First row, second cell in second table</td>
        </tr>
        <tr>
            <td>Second row, first cell in second table</td>
            <td>Second row, second cell in second table</td>
        </tr>
    </table>
</body>
</html>

當我們執行上述程式時,每個表格中的最後一行表格行將以黃色背景突出顯示。

示例 3

在這裡,我們選擇所有 <div> 元素的最後一個 <p> 元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Apply an italic font style to the first <p> child of each <div>
            $("div p:first-child").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <div style="border: 1px solid black;">
        <p>First paragraph in first div</p>
        <p>Second paragraph in first div</p>
    </div>
    <br>
    <div style="border: 1px solid black;">
        <p>First paragraph in second div</p>
        <p>Second paragraph in second div</p>
    </div>
</body>
</html>

執行上述程式後,所有 <div> 元素的最後一個 <p> 元素將以黃色背景突出顯示。

jquery_ref_selectors.htm
廣告