早期 jQuery 版本中,使用 .attr("checked", true/false) 或 .removeAttr("checked") 操作 checkbox 在 Firefox 下表現異常 (全選後反選失效、狀態不同步)。根因在於 **Attribute (屬性) 與 Property (屬性) 的混淆**。本文解析原因並給出跨瀏覽器穩健方案。
// ❌ 錯誤示範:attr 操作 attribute,不改變 DOM property
$("#checkAll").click(function(){
$("input[type='checkbox']").attr("checked", true); // 全選
});
$("#invert").click(function(){
$("input[type='checkbox']").each(function(){
if ($(this).attr("checked")) { // 讀取 attribute
$(this).removeAttr("checked"); // 移除 attribute
} else {
$(this).attr("checked", "checked");
}
});
});
checked 是 **Boolean Property** (IDL 屬性),決定當前勾選狀態。checked **Attribute** (HTML 屬性) 僅表示**默認值** (defaultChecked)。.prop() 操作 Property,**.attr() 僅操作 Attribute**。.attr("checked", true) 只添加 HTML 屬性,不改變 Property,導致 UI 不變、提交值為 off。// ✅ 全選
$("#checkAll").click(function(){
$("input[type='checkbox']").prop("checked", true);
});
// ✅ 取消全選
$("#uncheckAll").click(function(){
$("input[type='checkbox']").prop("checked", false);
});
// ✅ 反選 (兩種寫法)
$("#invert").click(function(){
// 寫法 A:原生 property 切換 (最快、最穩)
$("input[type='checkbox']").each(function(){
this.checked = !this.checked;
});
// 寫法 B:jQuery prop + 回調函數
$("input[type='checkbox']").prop("checked", function(i, val){
return !val;
});
});
// ✅ 獲取選中值
var vals = $("input[type='checkbox']:checked").map(function(){ return this.value; }).get();
// 全選
function checkAll(name, flag = true) {
document.querySelectorAll(`input[name="${name}"]`).forEach(el => el.checked = flag);
}
// 反選
function toggleAll(name) {
document.querySelectorAll(`input[name="${name}"]`).forEach(el => el.checked = !el.checked);
}
// 獲取選中值
function getCheckedValues(name) {
return [...document.querySelectorAll(`input[name="${name}"]:checked`)].map(el => el.value);
}
.prop() 操作 checked/disabled/selected/readonly 等布爾屬性。:checked 選擇器或 .prop("checked"),勿用 .attr("checked")。el.checked = !el.checked**,無庫依賴、語義明確、性能最優。change 事件,通過 e.target.matches('input[type="checkbox"]') 判斷。理解 Attribute vs Property 區別是前端進階必修課,能徹底解決 checkbox、select、input 狀態同步的各種疑難雜症。