jQuery :lt() 選擇器



jQuery 中的 :lt() 選擇器用於選擇匹配集中索引小於指定索引的元素。此選擇器從集合中的第一個元素開始計數,索引為零 (0),依此類推。

語法

以下是 jQuery :lt() 選擇器的語法:

$(":lt(index)")

引數

以下是上述語法的描述:

  • index: 一個基於零的整數,表示要比較的索引。索引小於此值的元素將被選中。

示例 1

在以下示例中,我們使用 jQuery :lt() 選擇器來選擇索引小於 2 的列表元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li:lt(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>
    </ul>
</body>
</html>

執行上述程式後,第一個 (索引:0) 和第二個 (索引:1) 列表項將以黃色背景色突出顯示。

示例 2

在此示例中,我們選擇並隱藏索引小於 2 的表格行:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("tr:lt(2)").hide();
        });
    </script>
</head>
<body>
    <table border="1">
        <tr><td>Row 1</td></tr>
        <tr><td>Row 2</td></tr>
        <tr><td>Row 3</td></tr>
        <tr><td>Row 4</td></tr>
        <tr><td>Row 5</td></tr>
    </table>
</body>
</html>

執行後,索引小於 2 的表格行將被隱藏。

示例 3

這裡,我們選擇索引小於 2 的段落元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:lt(2)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>This is the first paragraph.</p>
    <p>This is the second paragraph.</p>
    <p>This is the third paragraph.</p>
</body>
</html>

第二個及以上的段落將以黃色背景色突出顯示。

jquery_ref_selectors.htm
廣告

© . All rights reserved.