jQuery 提供 .attr() 讀取/設定屬性、.removeAttr() 移除屬性,是 DOM 操作的核心工具。本文系統整理語法、重載形式、常見用法與現代原生替代方案。
| 語法 | 用途 | 回傳值 |
|---|---|---|
.attr(name) | 取得第一個匹配元素的屬性值 | String / undefined |
.attr(name, value) | 設定所有匹配元素的單一屬性 | jQuery (鏈式) |
.attr(object) | 批次設定多個屬性 {name: value, ...} | jQuery |
.attr(name, function) | 函式回傳值設定屬性,參數 (index, oldValue) | jQuery |
<img id="avatar" src="a.jpg" alt="頭像" data-user-id="123">
$('#avatar').attr('src'); // "a.jpg"
$('#avatar').attr('data-user-id'); // "123" (HTML5 data-* 也可用 .data())
$('#avatar').attr('nonexist'); // undefined
$('#avatar').attr('src', 'b.jpg');
$('#avatar').attr('alt', '新頭像');
$('#avatar').attr({
src: 'b.jpg',
alt: '切換後',
title: '點擊放大'
});
// 為所有圖片加上索引 data-index
$('img').attr('data-index', function(index) {
return index;
});
<img class="hover-img" src="images/a.jpg" alt="原圖" data-hover="images/b.jpg" data-hover-alt="切換後">
$('.hover-img').hover(
function() { // mouseenter
const $this = $(this);
$this.data('orig-src', $this.attr('src'))
.data('orig-alt', $this.attr('alt'))
.attr({ src: $this.data('hover'), alt: $this.data('hover-alt') });
},
function() { // mouseleave
const $this = $(this);
$this.attr({ src: $this.data('orig-src'), alt: $this.data('orig-alt') });
}
);
// 移除單一屬性
$('#avatar').removeAttr('alt');
// 移除多個屬性(空格分隔,jQuery 1.7+)
$('#avatar').removeAttr('alt title data-user-id');
內部呼叫原生 removeAttribute(),但自動處理 jQuery 物件集合與鏈式呼叫。
| 分類 | 屬性 | Property |
|---|---|---|
| 定義 | HTML 標籤屬性 | DOM 物件屬性 |
| 同步 | 單向:HTML → DOM 初始化 | 雙向即時同步 |
| 典型例子 | src, href, class, id, data-* | checked, selected, disabled, value, innerHTML |
| jQuery 方法 | .attr() / .removeAttr() | .prop() / .removeProp() |
// ❌ 錯誤:attr 只影響初始 HTML,不改變實際勾選狀態
$('#chk').attr('checked', true);
// ✅ 正確:prop 操作 DOM property
$('#chk').prop('checked', true);
$('#chk').prop('disabled', false);
const el = document.getElementById('avatar');
// 讀取
el.getAttribute('src'); // 等同 .attr('src')
el.hasAttribute('data-user-id'); // 檢查存在性
// 設定
el.setAttribute('src', 'b.jpg');
el.setAttribute('data-index', '5');
// 批次設定
['src', 'alt', 'title'].forEach(attr => el.setAttribute(attr, '...'));
// 移除
el.removeAttribute('alt');
// data-* 專用 API (自動轉型)
el.dataset.userId; // 讀取 data-user-id -> "123" (字串)
el.dataset.userId = '456'; // 寫入
delete el.dataset.userId; // 刪除
checked, selected, disabled, readonly, value, tabIndex 等布林/數值屬性。src, href, class, id, data-*, role, aria-* 等 HTML 屬性。.attr({...}) 減少 DOM 重繪。const $el = $('#id') 再操作。setAttribute/getAttribute 或 dataset。.attr() 處理 HTML 屬性,.prop() 處理 DOM Property,兩者分工明確。.removeAttr() 批次移除屬性。現代開發可直接使用原生 API,但理解兩者差異對維護舊專案、除錯複雜行為至關重要。