同一件事往往有好幾種寫法,jQuery 定位元素就是典型例子。以下用「找到第三個文字輸入框」當例子,把常見的四種寫法並列比較。
<html>
<table class="ed">
<tr>
<td><input type="text"></input></td>
<td><input type="text"></input></td>
<td><input type="button"></input></td>
<td><input type="text"></input></td>
</tr>
</table>
</html>
$(".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"。這四行分成兩組:一組用 input:text 這種簡寫的偽類別,另一組用 input[type='text'] 明確的屬性選擇器,兩者語意相同但後者意圖更清楚。
另一組差異在定位方式:.eq(3) 是先把整個集合取出來,再取索引 3 的元素,鏈式呼叫時比較好接續;:eq(3) 則是在選擇器階段就完成篩選。兩者結果一致,效能差異微小,挑一個團隊一致的風格就好。
順帶一提,範例中的索引是 3 而不是 2,因為 jQuery 的集合索引從 0 開始,而這裡的 :text 只會選到三個文字框(不含 button),所以索引 3 其實超出了範圍。若真要選第三個文字框,應寫成 eq(2)。這也是初學時最常出錯的地方之一。