要在同一層的多個 input 中挑出特定的那一個,jQuery 提供好幾種等價寫法。
<table class="ed">
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="button"></td>
<td><input type="text"></td>
</tr>
</table>
$(".ed input:text").eq(3)
$(".ed input:text:eq(3)")
$(".ed input[type='text']").eq(3)
$(".ed input[type='text']:eq(3)")
其中 .ed 對應 class="ed"。不難看出兩條軸線:一是用 jQuery 的 :text 簡寫還是用標準的屬性選擇器 [type='text'];二是用方法 .eq() 還是用選擇器內的 :eq()。
屬性選擇器是 CSS 標準,效能與可讀性都較好;:text 之類的位置與型別選擇器屬於 jQuery 擴充,無法在 querySelectorAll 中直接使用。至於 .eq() 與 :eq(),前者可以串在鏈式呼叫中間、也能接受負數索引(.eq(-1) 取最後一個),彈性更大,建議優先採用。
另外注意 :text 只匹配 type="text",並不包含 textarea;若要一次抓所有文字輸入元件,用 $(".ed input, .ed textarea") 再自行過濾會更明確。