- jQuery 教程
- jQuery - 首頁
- jQuery - 路線圖
- jQuery - 概述
- jQuery - 基礎
- jQuery - 語法
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 屬性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 新增元素
- jQuery - 刪除元素
- jQuery - 替換元素
- jQuery CSS 操作
- jQuery - CSS 類
- jQuery - 尺寸
- jQuery - CSS 屬性
- jQuery 效果
- jQuery - 效果
- jQuery - 動畫
- jQuery - 鏈式操作
- jQuery - 回撥函式
- jQuery 遍歷
- jQuery - 遍歷
- jQuery - 遍歷祖先元素
- jQuery - 遍歷子孫元素
- jQuery UI
- jQuery - 互動
- jQuery - 小部件
- jQuery - 主題
- jQuery 參考
- jQuery - 選擇器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍歷
- jQuery - 其他
- jQuery - 屬性
- jQuery - 工具函式
- jQuery 外掛
- jQuery - 外掛
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用資源
- jQuery - 問答
- jQuery - 快速指南
- jQuery - 有用資源
- jQuery - 討論
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
廣告
