使用 $("input").attr("checked", "checked") 後,Chrome DevTools 顯示 DOM 屬性已有 checked="checked",但畫面上核取方塊**仍顯示未勾選**。
| 概念 | Attribute (屬性) | Property (特性/屬性值) |
|---|---|---|
| 定義 | HTML 標籤上寫死的初始值 | DOM 物件在記憶體中的即時狀態 |
| 同步方向 | 初始化時 Attribute → Property | 用戶互動/JS 修改時 Property 變化,**不回寫 Attribute** |
| checked | checked="checked" (字串) | true/false (布林) |
attr() 操作 Attribute,**不改變 Property**,故 UI 不更新。prop() 直接操作 Property,**即時生效**。
// 設定勾選
$("input[type='checkbox']").prop("checked", true);
// 取消勾選
$("input[type='checkbox']").prop("checked", false);
// 切換狀態
$("input[type='checkbox']").prop("checked", function(i, val) {
return !val;
});
// 推薦
if ($("input[type='checkbox']").prop("checked")) { ... }
if ($("input[type='checkbox']").is(":checked")) { ... }
// 原生(最快)
if (document.querySelector("input[type='checkbox']").checked) { ... }
attr() 混淆了 Attribute/Property,attr("checked") 返回 true/false。attr() 返回 "checked" 字串,prop() 返回布林。**導致大量舊代碼失效**。attr("checked") 再次返回布林並同步 Property,**但語意不清,官方強烈建議改用 prop()**。// 都要用 prop()
.selectedIndex, .tagName, .nodeName, .nodeType, .ownerDocument,
.defaultChecked, .defaultSelected, .disabled, .selected, .readonly,
.required, .hidden, .multiple, .autofocus, .autoplay, .controls, .loop
.prop()。.attr()。element.checked = true / element.disabled = false,零依賴、效能最高。