正確方法:使用 .prop()
// 設置禁用
$('#areaSelect').prop('disabled', true); // 布爾屬性
$('#areaSelect').prop('disabled', false); // 啟用
// 移除屬性(等同於 prop false)
$('#areaSelect').removeAttr('disabled'); // 徹底移除 DOM 屬性
$('#areaSelect').prop('disabled', false); // 推薦:語義清晰
為什麼不用 .attr()?
| 屬性類型 | 例子 | .attr() 行為 | .prop() 行為 | 正確選擇 |
| 布爾屬性 | disabled, checked, selected, readonly, required | 設置字符串 "disabled",移除屬性才能解除;獲取返回 "disabled" 或 undefined | 設置 true/false 直接對應 DOM property,獲取返回 true/false | .prop() |
| 普通屬性 | id, class, src, href, value, data-* | 操作 HTML attribute | 操作 DOM property(通常同步) | .attr() 或 .prop() 均可,但語義上 attribute 用 .attr() |
| value | input.value | 獲取初始 HTML 值 | 獲取當前用戶輸入值 | .val() 或 .prop('value') |
代碼演示差異
<input id="test" type="checkbox" checked>
<script>
const el = document.getElementById('test');
// jQuery
console.log('attr checked:', $('#test').attr('checked')); // "checked" (字符串)
console.log('prop checked:', $('#test').prop('checked')); // true (布爾)
// 取消勾選
$('#test').prop('checked', false);
console.log('prop after:', $('#test').prop('checked')); // false
console.log('attr after:', $('#test').attr('checked')); // "checked" (HTML 屬性未變!)
// 正確移除
$('#test').removeAttr('checked');
console.log('attr after remove:', $('#test').attr('checked')); // undefined
</script>
批量操作最佳實踐
// 禁用表單所有輸入
$('form :input').prop('disabled', true);
// 啟用特定
$('#submitBtn').prop('disabled', false);
// 表單重置時
$('form')[0].reset(); // 原生 reset() 會自動清除 disabled? 不會,需手動
$('form :input').prop('disabled', false);
原生 JS 等價
// 設置
el.disabled = true;
// 移除
el.disabled = false;
// 或
el.removeAttribute('disabled');