萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery Checkbox 遍歷與操作全攻略:全選、取值、狀態判斷

核心 API 速查

需求推薦寫法(jQuery 1.6+)舊版寫法(≤1.5)
全選/取消全選$('#chkAll').on('change', function(){ $('input[name=items]').prop('checked', this.checked); });.attr('checked', this.checked)
獲取所有被選中的值const vals = $('input[name=items]:checked').map(function(){ return this.value; }).get();.attr('checked') 判斷
判斷單個 checkbox 狀態$('#chkId').prop('checked') 返回 true/false$('#chkId').attr('checked')
設定單個 checkbox 狀態$('#chkId').prop('checked', true)$('#chkId').attr('checked', true)
遍歷並執行邏輯$('input[name=items]:checked').each(function(){ console.log(this.value); });同左

完整示例:全選與批量取值

<div id="divContent">
  <label><input type="checkbox" id="chkAll"> 全選</label><br/>
  <label><input type="checkbox" name="chk_list" value="1"> 選項 1</label>
  <label><input type="checkbox" name="chk_list" value="2"> 選項 2</label>
  <label><input type="checkbox" name="chk_list" value="3"> 選項 3</label>
</div>
<button id="btnGet">獲取選中值</button>

<script>
$(function () {
  // 全選/取消
  $('#chkAll').on('change', function () {
    $('input[name="chk_list"]').prop('checked', this.checked);
  });
  
  // 反向:子項全選時自動勾選全選框
  $('input[name="chk_list"]').on('change', function () {
    const all = $('input[name="chk_list"]');
    const checked = all.filter(':checked');
    $('#chkAll').prop('checked', all.length === checked.length);
    // 若需支援半選狀態(indeterminate)
    $('#chkAll').prop('indeterminate', checked.length > 0 && checked.length < all.length);
  });
  
  // 批量獲取值
  $('#btnGet').on('click', function () {
    const vals = $('input[name="chk_list"]:checked').map(function () {
      return this.value;
    }).get(); // ['1','2']
    console.log('選中值:', vals.join(','));
  });
});
</script>

關鍵陷阱與最佳實踐

1. prop() vs attr()

jQuery 1.6+ 明確區分:屬性 用 attr(),屬性狀態(checked、selected、disabled、readonly)用 prop()。attr('checked') 返回初始 HTML 值("checked" 或 undefined),不反映當前狀態。

2. 選擇器空格陷阱

// ❌ 錯誤:空格表示後代選擇器,會找不到同一元素上的多個屬性
$('input[type="checkbox"] [name="chk_list"]')

// ✅ 正確:多屬性選擇器緊湊書寫
$('input[type="checkbox"][name="chk_list"]')

// ✅ 更簡潔:直接用 name 選擇器(若頁面無同名非 checkbox)
$('input[name="chk_list"]')

3. 動態新增的 checkbox 事件委託

// 使用事件委託,支援動態插入
$('#divContent').on('change', 'input[name="chk_list"]', function () {
  // 處理邏輯
});

4. 表單提交時只傳遞勾選值

原生表單提交會自動忽略未勾選的 checkbox。若需 AJAX 手動構造數據:

const formData = $('input[name="chk_list"]:checked').serializeArray();
// [{name: "chk_list", value: "1"}, {name: "chk_list", value: "3"}]

結語

掌握 prop()、:checked 選擇器、.map().get() 取值模式,即可輕鬆應對 90% 的 checkbox 交互場景。記住:狀態用 prop,屬性用 attr;選擇器屬性之間不要加空格。

copyright © 萬盛學電腦網 all rights reserved