在資料表格、批次操作介面中,「全選/取消全選」是高頻需求。本文提供原生 JS 與 jQuery 兩種實現,並針對動態新增元素、效能、語義化提出最佳實踐建議。
var tog = false; // 初始狀態
$('a.toggle-all').click(function() {
$('input[type="checkbox"]').prop('checked', !tog); // 使用 prop 而非 attr
tog = !tog;
});
關鍵點:
.prop('checked', bool) 而非 .attr('checked', ...)。checked 是 property(即時狀態),attr 僅反映初始 HTML 屬性,jQuery 1.6+ 強烈建議用 prop。tog 記錄當前全選狀態,避免重複查詢 DOM。// 綁定在容器上,支援動態新增的 checkbox(事件代理)
document.getElementById('tableContainer').addEventListener('click', function(e) {
if (e.target.matches('a.toggle-all')) {
const checkboxes = this.querySelectorAll('input[type="checkbox"]');
const shouldCheck = !this.dataset.allChecked; // 使用 data-* 儲存狀態
checkboxes.forEach(cb => cb.checked = shouldCheck);
this.dataset.allChecked = shouldCheck;
}
});
優點:無 jQuery 依賴、事件代理自動支援動態元素、狀態存在 DOM dataset 避免全域變數污染。
<button type="button" id="selectAll" aria-pressed="false">
<span class="label">全選</span>
</button>
<script>
const btn = document.getElementById('selectAll');
const checkboxes = () => document.querySelectorAll('#dataTable input[type="checkbox"]');
btn.addEventListener('click', () => {
const pressed = btn.getAttribute('aria-pressed') === 'true';
const next = !pressed;
checkboxes().forEach(cb => cb.checked = next);
btn.setAttribute('aria-pressed', next);
btn.querySelector('.label').textContent = next ? '取消全選' : '全選';
});
</script>
無障礙加分:aria-pressed 告知螢幕閱讀器按鈕狀態,文字動態切換提升可用性。
$('#table input:checkbox') 只會抓當下存在的元素,需用事件代理或操作前重新查詢。.prop('checked', true) 可能造成明顯延遲,可考慮分批次 requestAnimationFrame 執行或使用虛擬滾動。disabled 的 checkbox 不會隨表單送出,全選邏輯勿誤將其設為 disabled。選擇適合專案技術棧的方案,記住 prop > attr、善用事件代理、重視無障礙,就能寫出健壯的全選功能。