嗨!看到你問jQuery的遍歷方法,我超開心的!這兩個方法就像給DOM元素裝了"導航按鈕",讓你能輕鬆找到集合中的第一個或最後一個元素。😄 作為前端老友,我來給你整點實用的,保證你用得飛起!
📌 first() 和 last() 是啥?
- first():返回匹配元素集合中的第一個元素
- last():返回匹配元素集合中的最後一個元素
💡 小貼士:它們是jQuery遍歷方法中最基礎的"過濾器",常用於操作列表、表格等需要定位首尾元素的場景。
🧾 語法説明
// 選取所有匹配元素,然後取第一個
$(selector).first();
// 選取所有匹配元素,然後取最後一個
$(selector).last();
💻 超實用代碼例子
✅ 示例1:操作列表的首尾元素
<!DOCTYPE html>
<html>
<head>
<title>jQuery first() & last() 示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
ul { margin: 20px 0; padding: 0; list-style: none; }
li { padding: 8px; margin: 5px; background: #f0f0f0; }
.first-item { background: #4CAF50; color: white; }
.last-item { background: #FFC107; color: black; }
</style>
</head>
<body>
<h2>水果列表</h2>
<ul>
<li>蘋果</li>
<li>香蕉</li>
<li>橙子</li>
<li>葡萄</li>
<li>草莓</li>
</ul>
<script>
// 1. 為第一個水果添加綠色背景
$('li').first().addClass('first-item');
// 2. 為最後一個水果添加橙色背景
$('li').last().addClass('last-item');
// 3. 也可以這樣寫(鏈式調用)
$('li').first().css('font-weight', 'bold');
$('li').last().css('font-style', 'italic');
console.log("第一個水果:", $('li').first().text());
console.log("最後一個水果:", $('li').last().text());
</script>
</body>
</html>
效果預覽:
- 第一個水果(蘋果)顯示為綠色背景+加粗
- 最後一個水果(草莓)顯示為橙色背景+斜體
- 控制枱會打印出"蘋果"和"草莓"
✅ 示例2:操作嵌套元素
<div class="container">
<p>第一個段落</p>
<p>第二個段落</p>
<p>第三個段落</p>
</div>
<script>
// 選取第一個div內的第一個p元素
$('.container p').first().css('color', 'blue');
// 選取第一個div內的最後一個p元素
$('.container p').last().css('font-weight', 'bold');
// 也可以這樣寫
$('.container p:first').css('text-decoration', 'underline');
$('.container p:last').css('text-transform', 'uppercase');
</script>
💡 小技巧:
.first()和.last()與 CSS 偽類:first和:last效果類似,但 jQuery 方法更靈活,可以鏈式調用。
🌟 和eq()方法的對比
|
方法
|
作用
|
索引
|
示例
|
|
|
取第一個
|
0
|
|
|
|
取最後一個
|
n-1
|
|
|
|
取指定索引
|
0-based
|
|
💡 注意:
eq()的索引是從0開始的,所以第一個元素索引是0,不是1。