萬盛學電腦網

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

jQuery 複選框全選、反選、全不選:按鈕觸發版完整實作

延續上一篇,本文示範以**按鈕**而非核取方塊觸發全選/反選/全不選的常見模式,並處理動態新增列、表單提交序列化等實務細節。

HTML 結構

<fieldset>
  <legend>水果選擇</legend>
  <div id="fruit-list">
    <label><input type="checkbox" name="fruit" value="apple"> 蘋果</label>
    <label><input type="checkbox" name="fruit" value="banana"> 香蕉</label>
    <label><input type="checkbox" name="fruit" value="pineapple"> 鳳梨</label>
    <label><input type="checkbox" name="fruit" value="strawberry"> 草莓</label>
    <label><input type="checkbox" name="fruit" value="pear"> 梨子</label>
  </div>
  <div class="actions">
    <button type="button" id="btn-select-all">全選</button>
    <button type="button" id="btn-invert">反選</button>
    <button type="button" id="btn-select-none">全不選</button>
  </div>
</fieldset>

jQuery 實作(支援動態新增)

(function($) {
  const $list = $('#fruit-list');
  const $checkboxes = () => $list.find('input[name="fruit"]'); // 函式取得最新集合

  // 全選
  $('#btn-select-all').on('click', function() {
    $checkboxes().prop('checked', true);
  });

  // 全不選
  $('#btn-select-none').on('click', function() {
    $checkboxes().prop('checked', false);
  });

  // 反選
  $('#btn-invert').on('click', function() {
    $checkboxes().each(function() {
      this.checked = !this.checked; // 原生 DOM 操作最快
    });
  });

  // 動態新增項目示範
  $('#btn-add').on('click', function() {
    const newVal = 'fruit-' + Date.now();
    $list.append(``);
  });

  // 表單提交:取得所有勾選值
  $('#submit-form').on('submit', function(e) {
    e.preventDefault();
    const selected = $checkboxes().filter(':checked').map(function() {
      return this.value;
    }).get();
    console.log('提交資料:', selected);
    // $.ajax({ data: { fruits: selected } });
  });
})(jQuery);

進階:取得「未勾選」的值

const unselected = $checkboxes().not(':checked').map(function() {
  return this.value;
}).get();

效能優化:大量資料時的處理

  • 使用 this.checked = ... 原生屬性存取,避免 jQuery 封裝開銷。
  • 批次操作後**單次觸發**事件:$checkboxes().trigger('change')。
  • 虛擬清單:僅渲染可視區域,配合 IntersectionObserver。

無障礙注意事項

  • 按鈕必須有 type="button" 防止誤觸發表單提交。
  • 提供 aria-label 或可見文字說明按鈕功能。
  • 確保焦點順序邏輯:列表 → 操作按鈕 → 提交。

Vanilla JS 等效實作

const list = document.getElementById('fruit-list');
const getCheckboxes = () => list.querySelectorAll('input[name="fruit"]');

document.getElementById('btn-select-all').addEventListener('click', () => {
  getCheckboxes().forEach(cb => cb.checked = true);
});

document.getElementById('btn-invert').addEventListener('click', () => {
  getCheckboxes().forEach(cb => cb.checked = !cb.checked);
});

document.getElementById('btn-select-none').addEventListener('click', () => {
  getCheckboxes().forEach(cb => cb.checked = false);
});

按鈕觸發模式在「批次操作工具列」場景極常見,掌握核心邏輯與無障礙細節,即可快速套用至各類管理後台。

copyright © 萬盛學電腦網 all rights reserved