
- 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 :nth-child() 選擇器
jQuery 中的:nth-child() 選擇器用於選擇其父元素的第 n 個子元素。
此方法允許您根據元素在其父元素的子元素列表中的位置來選擇元素,使用“索引”和“公式”引數。
語法
以下是 jQuery :nth-child() 選擇器的語法:
:nth-child(n|even|odd|formula)
引數
以下是上述語法的描述:
- n: 選擇其父元素的第 n 個子元素。索引從 1 開始,而不是 0。
- even|odd: 分別選擇偶數和奇數編號的子元素。
- formula: 根據數學公式 (an+b) 選擇元素。“a” 和“b” 是整數。
示例 1
在以下示例中,我們使用 jQuery :nth-child() 選擇器來選擇 <ul> 中的第 2 個 <li> 元素:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("li:nth-child(2)").css("background-color", "yellow"); }); </script> </head> <body> <h2>List Example</h2> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul> </body> </html>
執行上述程式後,作為其父元素 (<ul>) 的第二個子元素的 <li> 將以黃色背景顏色突出顯示。
示例 2
在此示例中,我們使用“odd”和“even”引數來選擇奇數和偶數子 (<li>) 元素:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("li:nth-child(odd)").css("background-color", "yellow"); $("li:nth-child(even)").css("background-color", "lightblue"); }); </script> </head> <body> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> <li>Item 6</li> </ul> </body> </html>
執行程式後,奇數編號的列表項將以黃色背景顏色突出顯示,偶數編號的項將以淺藍色突出顯示。
示例 3
p:nth-child(3n+1) 選擇 <div> 元素內的每個第一個和後續的第三個段落:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p:nth-child(3n+1)").css("background-color", "yellow"); }); </script> </head> <body> <div> <p>Paragraph 1</p> <p>Paragraph 2</p> <p>Paragraph 3</p> <p>Paragraph 4</p> <p>Paragraph 5</p> <p>Paragraph 6</p> <p>Paragraph 7</p> <p>Paragraph 8</p> </div> </body> </html>
執行上述程式後,所選元素將以黃色背景顏色突出顯示。
jquery_ref_selectors.htm
廣告