.attr() 存取。.prop() 存取。⚠️ **`readonly`、`disabled`、checked、selected 等布林屬性,必須用 .prop() 操作**,.attr() 在 jQuery 1.6+ 行為不一致,易產生 Bug。
// 設為唯讀
$("input").prop("readonly", true);
// 移除唯讀
$("input").prop("readonly", false);
// 判斷是否唯讀
if ($("input").prop("readonly")) { ... }
// 設為停用
$("input, select, button").prop("disabled", true);
// 啟用
$("input, select, button").prop("disabled", false);
// 判斷
if ($("input").prop("disabled")) { ... }
// 這些在舊版 jQuery 可能運作,但語意錯誤、行為不穩定
$("input").attr("readonly", "readonly"); // 設定屬性字串
$("input").attr("readonly", true); // 邏輯混淆
$("input").removeAttr("readonly"); // 移除屬性節點
$("input").attr("readonly", ""); // 設空字串(無效)
問題:.attr() 操作的是 HTML 屬性節點,不一定同步更新 DOM property,導致 UI 與狀態不同步。
// 僅針對文字輸入框設 readonly
$("input[type='text'], textarea").prop("readonly", true);
// 僅針對可互動表單元素設 disabled
$("input, select, textarea, button").prop("disabled", true);
$("input").prop("readonly", function (i, val) {
return !val; // 依當前值翻轉
});
function setFormDisabled(formSelector, disabled) {
$(formSelector)
.find("input, select, textarea, button")
.prop("disabled", disabled);
}
// 使用
setFormDisabled("#myForm", true); // 全部停用
setFormDisabled("#myForm", false); // 全部啟用
input[readonly] {
background-color: #f5f5f5;
cursor: not-allowed;
}
input:disabled {
opacity: 0.6;
cursor: not-allowed;
}
| 誤區 | 正確做法 |
|---|---|
| 用 .attr("readonly", true) | .prop("readonly", true) |
| 用 .attr("disabled", "disabled") | .prop("disabled", true) |
| 判斷 if ($(el).attr("readonly")) | if ($(el).prop("readonly")) |
| 移除用 .attr("readonly", "") | .prop("readonly", false) |
布林屬性一律用 .prop() 操作布林值(true/false)。批量設定時搭配精準選擇器與封裝函式,程式碼更乾淨、行為更可預期。