萬盛學電腦網

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

jQuery prop() vs attr() 核心差異與使用準則

jQuery 1.6+ 引入 prop() 後,開發者常困惑何時用 prop()、何時用 attr()。核心原則只有一句:

HTML 元素固有屬性 → 用 prop()
自訂 DOM 屬性 → 用 attr()

固有屬性(Properties)

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)

自訂屬性(Attributes)

開發者自行加上、非標準屬性:

<a href="#" id="link1" action="delete">刪除</a>
// action 為自訂屬性
$("a").attr("action"); // "delete"
$("a").prop("action"); // undefined ❌

表單元素狀態屬性(checked/selected/disabled/readonly)

這些是**固有屬性**,必須用 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" (字串) ⚠️ 語意不對

版本演進脈絡

  • jQuery < 1.6:attr() 同時處理屬性與特性,行為不一致
  • jQuery 1.6+:分離 prop()(Properties)與 attr()(Attributes)
  • jQuery 1.9+:attr("checked") 不再回傳布林值,僅回傳屬性字串

快速判斷表

屬性類型正確方法
id, class, href, src, title固有prop()
checked, selected, disabled, readonly, value固有(狀態)prop()
data-*, 任意自訂屬性自訂attr()
style (CSSStyleDeclaration)固有prop() / .css()
copyright © 萬盛學電腦網 all rights reserved