jQuery :last 選擇器



:last 選擇器是一個 jQuery 選擇器,用於選擇匹配元素集合中的最後一個元素。

當我們將此方法應用於一組匹配的元素時,它將返回該集合中找到的最後一個元素。如果沒有任何元素與選擇器表示式匹配,則返回一個空的 jQuery 物件。

注意:如果要選擇匹配元素集合中的第一個元素,則需要使用:first 選擇器。

語法

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

$("selector:last")

引數

以下是上述語法的解釋:

  • selector:這是一個 CSS 選擇器的佔位符。它指定選擇元素的條件。例如
  • "div" 選擇所有 <div> 元素。

  • ".class" 選擇所有具有類 "class" 的元素。

  • "#id" 選擇具有 id "id" 的元素。

  • last:將選擇過濾到匹配集合中的最後一個元素。

示例 1

在下面的示例中,我們使用 :last 選擇器來選擇最後一個 "paragraph" 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
   <p>This is the first paragraph.</p>
   <p>This is the second paragraph.</p>
   <p>This is the third paragraph.</p>
<button>Click</button>
</body>
</html>

執行上述程式並單擊按鈕後,它將使用灰色背景色突出顯示最後一個 <p> 元素。

示例 2

在此示例中,我們使用 :last 選擇器選擇最後一個 <div> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("div:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
   <div>This is the first div.</div>
   <div>This is the second div.</div>
   <div>This is the third div.</div>
<button>Click</button>
</body>
</html>

執行後單擊按鈕,它將選擇 DOM 中的最後一個 <div> 元素。

示例 3

在這裡,我們使用 :last 選擇器選擇具有類 "highlight" 的最後一個元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $(".highlight:last").css("background-color", "grey");
    })
});
</script>
</head>
<body>
<p class="highlight">This is the first paragraph.</p>
<p>This is a second paragraph.</p>
<p class="highlight">This is LAST paragraph.</p>
<button>Click</button>
</body>
</html>

執行上述程式後,它將選擇具有類 "highlight" 的最後一個元素,並以灰色背景色突出顯示。

jquery_ref_selectors.htm
廣告
© . All rights reserved.