這是最容易與 :eq() 搞混的一個。關鍵差異有兩點:索引從 1 開始(不是 0),而且是「每個父元素各自算一次」,不像 :eq() 是在整個結果集合裡全域計數。
支援的寫法::nth-child(even)、:nth-child(odd)、:nth-child(3n)、:nth-child(2)、:nth-child(3n+1)、:nth-child(3n+2)。
<ul><li>John</li><li>Karl</li><li>Brandon</li></ul>
<ul><li>Glen</li><li>Tane</li><li>Ralph</li></ul>
$("ul li:nth-child(2)"); // [ <li>Karl</li>, <li>Tane</li> ]
同樣是「每個父元素各算一次」,這與只選到單一元素的 :first/:last 有本質差異。
$("ul li:first-child"); // [ <li>John</li>, <li>Glen</li> ]
$("ul li:last-child"); // [ <li>Brandon</li>, <li>Ralph</li> ]
$("ul li:only-child"); // [ <li>Glen</li> ](只有第二個 ul 的 li 是獨子)
選到 input、textarea、select、button 四種標籤,不限 type。
$(":text") // 單行文字框
$(":password") // 密碼框
$(":radio") // 單選鈕
$(":submit") // 提交鈕
其餘同理::image、:reset、:button、:file、:hidden、:checkbox。
$("input:checked") // 已勾選的 checkbox / radio
$("select option:selected") // 選中的 option
$("input:enabled") / $("input:disabled")
$("input:selected") // 同 :checked 的 select 版本寫法
:text、:radio 這類寫法看起來簡潔,但 jQuery 內部實作是遍歷全部元素再逐一判斷 type,在有大量表單的頁面上效能明顯不如屬性選擇器。等價且更快的寫法是:
$("input:text") → $("input[type=text]")
$("input:radio") → $("input[type=radio]")
$(":checkbox:checked") → $("input[type=checkbox]:checked")
差別在於前者靠 jQuery 迴圈、後者能交給瀏覽器的 querySelectorAll 原生處理。表單量小時差異不明顯,但養成習慣沒壞處。