首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

jQuery :checked 選擇器為什麼也會選中 select 的 option 元素?

     編輯:程式設計疑難解答

jQuery :checked 選擇器不僅匹配 checkbox 和 radio,也匹配 select 中被選中的 option 元素。這是官方設計行為。

官方文檔說明

jQuery( ":checked" )
The :checked selector works for checkboxes, radio buttons, and options of select elements.

來源:jQuery API 文檔

示例

<select id="fruit">
  <option value="1">Apple</option>
  <option value="2" selected>Banana</option>
  <option value="3">Cherry</option>
</select>

<script>
  $('#fruit option:checked').val();  // 返回 "2"
  $('#fruit:checked').val();         // 同樣返回 "2"(select 本身也被視為 checked)
</script>

實際應用場景

  • 統一獲取表單中所有「已選」項:$('input:checked, select option:checked') 或簡寫 $(':checked')(包含 select 的選中 option)。
  • 若需區分類型,可用 input:checkbox:checked、input:radio:checked、select option:checked 分別選擇。

總結

:checked 選中 select option 是標準特性,非 Bug。理解此行為可簡化表單值獲取代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved