jQuery 1.6+ 引入 .prop() 區分「屬性」與「特性」,解決長期以來 .attr() 混淆導致的 Bug(特別是 checkbox、selectedIndex、disabled 等)。本文深度解析兩者本質區別、適用場景、常見誤區與最佳實踐。
| 概念 | Attribute (特性/HTML屬性) | Property (屬性/DOM屬性) |
|---|---|---|
| 定義位置 | HTML 標籤屬性 | DOM 節點對象屬性 |
| 初始值來源 | 解析 HTML 時設置 | 瀏覽器根據特性初始化,隨交互實時變化 |
| 同步關係 | 部分雙向同步(如 id, title, class) | 大多數單向:特性→屬性初始化,後續不同步 |
| 典型例子 | type="checkbox", value="txt", class="c" | checked, selectedIndex, disabled, value(輸入框當前值) |
<input type="checkbox" id="chk" checked>
// 頁面載入後,用戶取消勾選
// 當前狀態:
$('#chk').attr('checked'); // "checked" (字符串) — HTML 初始特性不變
$('#chk').prop('checked'); // false (布爾) — 實際勾選狀態
// 程式設置勾選
$('#chk').prop('checked', true); // 正確:更新 DOM 屬性,UI 即時響應
$('#chk').attr('checked', 'checked'); // 僅修改 HTML 特性,UI 不一定更新(視瀏覽器)
結論:凡涉及布爾狀態、動態變化的 DOM 屬性(checked, selected, disabled, readonly, selectedIndex, value 等),一律用 .prop()。
| 場景 | 推薦方法 | 理由 |
|---|---|---|
| checkbox / radio 勾選狀態 | .prop('checked') | 布爾屬性,實時狀態 |
| select 下拉框選中索引 | .prop('selectedIndex') | 數字屬性 |
| input/textarea 當前值 | .val() / .prop('value') | value 屬性隨輸入變化 |
| disabled / readonly 狀態 | .prop('disabled') | 布爾屬性 |
| HTML 標準屬性 (id, name, class, href, src, data-*) | .attr() | 特性與屬性同步,或需獲取初始 HTML 值 |
| 自定義屬性 (data-xxx) | .data() / .attr('data-xxx') | .data() 有緩存與類型轉換,.attr() 讀原始字符串 |
| 表單提交序列化 | .serialize() / .serializeArray() | 內部使用 .prop() 獲取當前值 |
// 刪除 DOM 屬性(如移除 checked 狀態)
$('#chk').removeProp('checked'); // 極少用,慎用!會徹底刪除 DOM 屬性,後續無法再 prop('checked',true) 恢復
// 刪除 HTML 特性
$('#element').removeAttr('disabled'); // 正確:移除 disabled 特性,元素恢復可用
幾乎不需要removeProp,只需prop('checked', false)取消勾選。
.attr(),內部嘗試模擬 property 行為,導致 checkbox 等場景 Bug 頻出。.attr() 對 boolean 屬性的兼容行為,但官方強烈建議遷移至 .prop()。.prop() 處理所有 DOM 屬性,.attr() 僅用於 HTML 特性操作。$.fn.formState = function (action, data) {
var $form = this;
if (action === 'get') {
var state = {};
$form.find('input,select,textarea').each(function () {
var $el = $(this), type = $el.attr('type'), tag = this.tagName.toLowerCase();
if (type === 'checkbox' || type === 'radio') {
state[$el.attr('name')] = $el.prop('checked');
} else if (tag === 'select') {
state[$el.attr('name')] = $el.val();
} else {
state[$el.attr('name')] = $el.val();
}
});
return state;
} else if (action === 'set') {
$.each(data, function (name, val) {
var $el = $form.find('[name="' + name + '"]');
if ($el.is(':checkbox,:radio')) {
$el.prop('checked', !!val);
} else {
$el.val(val);
}
});
}
};
// 用法
var data = $('#myForm').formState('get');
$('#myForm').formState('set', data);
徹底理解 Attribute vs Property,正確選擇 .prop() / .attr(),是寫出零 Bug 表單交互的關鍵。