jQuery 1.6+ 引入 prop() 後,開發者常困惑何時用 prop()、何時用 attr()。核心原則只有一句:
HTML 元素固有屬性 → 用
prop()
自訂 DOM 屬性 → 用attr()
W3C 標準定義、IDE 智能提示出現的屬性:
<a href="https://baidu.com" target="_self" class="btn">百度</a> // href、target、class 皆為固有屬性
$("a").prop("href"); // "https://baidu.com"
$("a").prop("target"); // "_self"
$("a").prop("className"); // "btn" (注意:class 對應 className)
開發者自行加上、非標準屬性:
<a href="#" id="link1" action="delete">刪除</a> // action 為自訂屬性
$("a").attr("action"); // "delete"
$("a").prop("action"); // undefined ❌
這些是**固有屬性**,必須用 prop():
<input id="chk1" type="checkbox" /> <input id="chk2" type="checkbox" checked="checked" />
$("#chk1").prop("checked"); // false ✅
$("#chk2").prop("checked"); // true ✅
$("#chk1").attr("checked"); // undefined ❌
$("#chk2").attr("checked"); // "checked" (字串) ⚠️ 語意不對
attr() 同時處理屬性與特性,行為不一致prop()(Properties)與 attr()(Attributes)attr("checked") 不再回傳布林值,僅回傳屬性字串| 屬性 | 類型 | 正確方法 |
|---|---|---|
| id, class, href, src, title | 固有 | prop() |
| checked, selected, disabled, readonly, value | 固有(狀態) | prop() |
| data-*, 任意自訂屬性 | 自訂 | attr() |
| style (CSSStyleDeclaration) | 固有 | prop() / .css() |