DIV CSS 佈局教程網

jQuery 學習筆記(三):子元素選擇器與表單選擇器
編輯:JQuery特效代碼     

一、子元素選擇器

:nth-child(index/even/odd/equation)

這是最容易與 :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-child / :last-child / :only-child

同樣是「每個父元素各算一次」,這與只選到單一元素的 :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 — 所有表單控制項

選到 input、textarea、select、button 四種標籤,不限 type。

依 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 原生處理。表單量小時差異不明顯,但養成習慣沒壞處。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved