萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

解決 jQuery 設定 Checkbox 狀態無效:prop() 與 attr() 的關鍵差異

現象

使用 $("input").attr("checked", "checked") 後,Chrome DevTools 顯示 DOM 屬性已有 checked="checked",但畫面上核取方塊**仍顯示未勾選**。

根本原因:Attribute vs Property

概念Attribute (屬性)Property (特性/屬性值)
定義HTML 標籤上寫死的初始值DOM 物件在記憶體中的即時狀態
同步方向初始化時 Attribute → Property用戶互動/JS 修改時 Property 變化,**不回寫 Attribute**
checkedchecked="checked" (字串)true/false (布林)

attr() 操作 Attribute,**不改變 Property**,故 UI 不更新。prop() 直接操作 Property,**即時生效**。

正確寫法(jQuery 1.6+)

// 設定勾選
$("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) { ... }

版本演進說明

  • jQuery < 1.6: attr() 混淆了 Attribute/Property,attr("checked") 返回 true/false。
  • jQuery 1.6: 嚴格分離,attr() 返回 "checked" 字串,prop() 返回布林。**導致大量舊代碼失效**。
  • jQuery 1.6.1+: 為相容性,attr("checked") 再次返回布林並同步 Property,**但語意不清,官方強烈建議改用 prop()**。

其他布林屬性同理

// 都要用 prop()
.selectedIndex, .tagName, .nodeName, .nodeType, .ownerDocument,
.defaultChecked, .defaultSelected, .disabled, .selected, .readonly,
.required, .hidden, .multiple, .autofocus, .autoplay, .controls, .loop

最佳實踐總結

  1. **任何布林屬性/狀態**一律用 .prop()。
  2. **自訂屬性**(data-*, aria-*, 非標準屬性)用 .attr()。
  3. 現代專案優先用原生 element.checked = true / element.disabled = false,零依賴、效能最高。
copyright © 萬盛學電腦網 all rights reserved