jQuery 提供四大核心方法存取元素內容與屬性,語意不同、回傳值不同、適用場景不同。搞清差異能避免「取不到值」「拿到帶標籤字串」等常見錯誤。
| 方法 | 用途 | 回傳值 | 可鏈式設值 | 典型場景 |
|---|---|---|---|---|
.text() | 純文字內容 | 字串(含後代文字,無標籤) | ✅ | 讀取/設定純文字,自動轉義 HTML |
.html() | HTML 內容 | 字串(含標籤) | ✅ | 讀取/替換內部 HTML 結構 |
.val() | 表單控制項值 | 字串/陣列(多選) | ✅ | input/select/textarea 取值、設值 |
.attr(name) | HTML 屬性 | 字串 / undefined | ✅ | 讀取/設定 id、src、href、data-* 等屬性 |
.prop(name) | DOM 屬性 | 布林/字串/物件 | ✅ | checked、disabled、selected、value(最新值) |
.data(key) | data-* 快取 | 任意型別(自動轉型) | ✅ | 讀寫 data-*,內部快取不同步回 DOM |
<div id="box">Hello <span>World</span></div>
<input id="chk" type="checkbox" checked>
$('#box').text(); // "Hello World"
$('#box').html(); // "Hello World"
$('#chk').attr('checked'); // "checked" (初始屬性)
$('#chk').prop('checked'); // true (當前狀態)
$('#chk').is(':checked'); // true (推薦判斷方式)
// 設定多個屬性
$('#img').attr({ src: 'a.jpg', alt: '圖片', title: '提示' });
// 設定多個 CSS (見 css() 方法)
$('#box').css({ color: 'red', fontSize: '14px' });
牢記:內容用 text/html/val,屬性用 attr/prop,資料用 data,各司其職,代碼更健壯。