利用屬性選擇器批量操作 checked 屬性:
// 全選
function selectAll() {
$('input[type="checkbox"]').prop('checked', true);
}
// 取消全選
function cancelAll() {
$('input[type="checkbox"]').prop('checked', false);
}
// 反選(可選增強)
function toggleAll() {
$('input[type="checkbox"]').each(function() {
this.checked = !this.checked;
});
}
建議使用
.prop('checked', true/false)而非.attr(),因checked是布爾屬性,prop語義更正確且跨瀏覽器一致。
<table>
<thead>
<tr><th><input type="checkbox" id="checkAll"></th>...</tr>
</thead>
<tbody>
<tr><td><input type="checkbox" class="row-check" value="1"></td>...</tr>
</tbody>
</table>
$('#checkAll').on('change', function() {
$('.row-check').prop('checked', this.checked);
});
$('.row-check').on('change', function() {
$('#checkAll').prop('checked', $('.row-check:checked').length === $('.row-check').length);
});
實現「全選勾選 → 全部勾選」、「單行取消 → 全選取消」的雙向同步。