萬盛學電腦網

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

jQuery Checkbox 全選/反選/主從聯動:父子勾選狀態同步完整實現

複雜表單中「全選」與「子項選中反向控制父項」是雙向綁定經典場景。本文提供兩個復用函數 selectAll() 與 checkSonCheckBox(),實現父控制子、子反向控制父的完整邏輯,含 indeterminate 半選狀態處理。

核心功能函數

1. selectAll:父控制子(全選/全不選)

/**
 * 全選/取消全選
 * @param {string} masterId - 父 checkbox id
 * @param {string} slaveClass - 子 checkbox 共同 class
 */
function selectAll(masterId, slaveClass) {
  var $master = $('#' + masterId);
  var $slaves = $('.' + slaveClass);
  
  $slaves.each(function() {
    var $this = $(this);
    if ($master.is(':checked')) {
      $this.prop('checked', true);
    } else {
      $this.prop('checked', false);
    }
  });
}

// 調用示例
$('#masterCheckbox').click(function() {
  selectAll('masterCheckbox', 'slaveItem');
});

2. checkSonCheckBox:子反向控制父(核心邏輯)

/**
 * 子項變化時更新父項狀態
 * @param {string} fatherId - 父 checkbox id
 * @param {string} sonClass - 子 checkbox 共同 class
 */
function checkSonCheckBox(fatherId, sonClass) {
  var $father = $('#' + fatherId);
  var $sons = $('.' + sonClass);
  
  $sons.off('click').on('click', function() {
    var $this = $(this);
    
    // 1. 維護視覺標記類(可選,配合 CSS)
    if ($this.is(':checked')) {
      $this.addClass('checked');
    } else {
      $this.removeClass('checked');
    }
    
    // 2. 判斷父項狀態
    var hasChecked = $sons.filter('.checked').length > 0; // 或 :checked
    var allChecked = $sons.filter(':checked').length === $sons.length;
    
    if (allChecked) {
      $father.prop('checked', true).prop('indeterminate', false);
    } else if (hasChecked) {
      $father.prop('checked', false).prop('indeterminate', true); // 半選狀態
    } else {
      $father.prop('checked', false).prop('indeterminate', false);
    }
  });
}

// 調用
checkSonCheckBox('masterCheckbox', 'slaveItem');

HTML 結構示例

<table id="dataTable">
  <thead>
    <tr>
      <th><input type="checkbox" id="masterCheckbox" /> 全選</th>
      <th>名稱</th>
      <th>操作</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="checkbox" class="slaveItem" value="1" /></td>
      <td>項目一</td>
      <td><button>編輯</button></td>
    </tr>
    <tr>
      <td><input type="checkbox" class="slaveItem" value="2" /></td>
      <td>項目二</td>
      <td><button>編輯</button></td>
    </tr>
    <!-- 更多行 -->
  </tbody>
</table>

<script>
$(function() {
  // 初始化綁定
  $('#masterCheckbox').click(function() {
    selectAll('masterCheckbox', 'slaveItem');
  });
  checkSonCheckBox('masterCheckbox', 'slaveItem');
});
</script>

關鍵技術點解析

prop() vs attr()

// ✅ 正確:操作屬性
$checkbox.prop('checked', true);
$checkbox.prop('checked', false);

// ❌ 錯誤:attr 操作屬性在 jQuery 1.6+ 行為不一致
$checkbox.attr('checked', 'checked'); // 可能只生效一次
$checkbox.removeAttr('checked');      // 移除屬性而非設置 false

indeterminate 半選狀態

  • 僅視覺效果(通常顯示為方塊/減號),不影響 checked 值
  • 只能通過 JS 設置:el.indeterminate = true 或 $el.prop('indeterminate', true)
  • HTML 無對應屬性

事件委託優化(動態行)

$('#dataTable').on('click', '.slaveItem', function() {
  // 此處邏輯同 checkSonCheckBox 內部
  // 適用於 AJAX 追加行、分頁重新渲染場景
});

原生 JS 現代實現(無依賴)

function setupCheckboxGroup(masterId, slaveSelector) {
  var master = document.getElementById(masterId);
  var slaves = document.querySelectorAll(slaveSelector);
  
  // 父控制子
  master.addEventListener('change', function() {
    slaves.forEach(function(s) { 
      if (!s.disabled) s.checked = master.checked; 
    });
  });
  
  // 子控制父
  slaves.forEach(function(s) {
    s.addEventListener('change', function() {
      var checked = Array.from(slaves).filter(function(s) { return s.checked; });
      master.checked = checked.length === slaves.length;
      master.indeterminate = checked.length > 0 && checked.length < slaves.length;
    });
  });
}

// 使用
setupCheckboxGroup('masterCheckbox', '.slaveItem');

後端接收數據格式

// 前端收集
var ids = $('.slaveItem:checked').map(function() { return this.value; }).get();
// ids = ["1", "2", "5"]

// 發送
$.post('/api/batch', { ids: ids }, function(res) { ... });

// 後端 (PHP 示例)
$ids = $_POST['ids']; // 數組 ["1","2","5"]
$ids = json_decode(file_get_contents('php://input'), true)['ids']; // JSON 請求

總結

雙向同步核心:prop('checked') 設置狀態、prop('indeterminate') 視覺半選、:checked 選擇器統計。現代項目推薦原生 JS 實現(無依賴、體積小),舊項目維護用 jQuery 版本即可。

copyright © 萬盛學電腦網 all rights reserved