
- 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 :first 選擇器
:first 選擇器是 jQuery 選擇器,用於選擇匹配元素集中第一個元素。
當應用於一組匹配的元素時,:first 選擇器返回該集中找到的第一個元素。如果沒有任何元素匹配選擇器表示式,則返回一個空的 jQuery 物件。
注意:如果我們想要選擇匹配元素集中最後一個元素,我們需要使用:last 選擇器。
語法
以下是 jQuery 中 :first 選擇器的語法:
$("selector:first")
引數
以下是上述語法的解釋:
- selector: 這是一個 CSS 選擇器。它指定選擇元素的條件。例如
"div" 選擇所有 <div> 元素。
".class" 選擇所有具有類 "class" 的元素。
"#id" 選擇具有 id "id" 的元素。
- first: 將選擇過濾到匹配集中第一個元素。
示例 1
在以下示例中,我們使用 :first 選擇器來選擇第一個 <p> 元素:
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p:first").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> <button>Click</button> </body> </html>
當我們點選按鈕時,DOM 中第一個段落元素將以黃色背景顏色突出顯示。
示例 2
這裡,我們使用 :first 選擇器選擇第一個 div 元素:
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("div:first").css("background-color", "yellow"); }) }); </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 中的第一個元素。
示例 3
在這個例子中,我們使用 :first 選擇器選擇第一個具有類 "highlight" 的元素:
<html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $(".highlight:first").css("background-color", "yellow"); }) }); </script> </head> <body> <p class="highlight">This is the FIRST paragraph.</p> <p>This is a normal paragraph.</p> <p class="highlight">This is another paragraph.</p> <button>Click</button> </body> </html>
執行上述程式後,它將選擇第一個具有類 "highlight" 的元素,並以黃色背景顏色突出顯示。
jquery_ref_selectors.htm
廣告