複雜表單中「全選」與「子項選中反向控制父項」是雙向綁定經典場景。本文提供兩個復用函數 selectAll() 與 checkSonCheckBox(),實現父控制子、子反向控制父的完整邏輯,含 indeterminate 半選狀態處理。
/**
* 全選/取消全選
* @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');
});
/**
* 子項變化時更新父項狀態
* @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');
<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>
// ✅ 正確:操作屬性
$checkbox.prop('checked', true);
$checkbox.prop('checked', false);
// ❌ 錯誤:attr 操作屬性在 jQuery 1.6+ 行為不一致
$checkbox.attr('checked', 'checked'); // 可能只生效一次
$checkbox.removeAttr('checked'); // 移除屬性而非設置 false
checked 值el.indeterminate = true 或 $el.prop('indeterminate', true)$('#dataTable').on('click', '.slaveItem', function() {
// 此處邏輯同 checkSonCheckBox 內部
// 適用於 AJAX 追加行、分頁重新渲染場景
});
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 版本即可。