<ul class="menu">
<li class="menulink">
<a href="#" id="item-101" data-role="admin">
<span>用戶管理</span>
</a>
</li>
<li class="menulink">
<a href="#" id="item-102" data-role="editor">
<span>內容管理</span>
</a>
</li>
</ul>
| 需求 | 選擇器 | 遍歷方法 | 屬性獲取 | 說明 |
|---|---|---|---|---|
獲取 <a> 的 id | $('.menulink > a') 或 $('.menulink a') | .each() / .map() | this.id 或 $(this).attr('id') | 直接選中 a 標簽 |
獲取 <li> 的 class | $('.menulink') | .each() | this.className 或 $(this).attr('class') | 選中 li 本身 |
獲取 <span> 文本 | $('.menulink span') 或 $('.menulink a span') | .each() | $(this).text() | 後代選擇器 |
| 獲取 data-* 屬性 | 同上 | 同上 | $(this).data('role') | .data() 自動轉換類型,緩存結果 |
// 獲取所有 a 的 id 數組
var ids = $('.menulink > a').map(function () {
return this.id; // 原生 DOM 屬性最快
}).get(); // 轉為原生數組 ["item-101", "item-102"]
// 獲取 data-role 對象數組
var roles = $('.menulink > a').map(function () {
return {
id: this.id,
role: $(this).data('role'), // 自動解析 JSON 類型
text: $(this).text().trim()
};
}).get();
console.log(roles);
// [
// {id: "item-101", role: "admin", text: "用戶管理"},
// {id: "item-102", role: "editor", text: "內容管理"}
// ]
var $a = $('.menulink > a').first();
var dom = $a[0]; // 獲取原生 DOM 元素
// 原生屬性(同步、無開銷)
dom.id; // "item-101"
dom.href; // 完整 URL
dom.getAttribute('data-role'); // "admin" (字符串)
dom.dataset.role; // "admin" (HTMLElement.dataset)
// jQuery 方法(統一接口、處理兼容性)
$a.attr('id'); // "item-101"
$a.attr('href'); // 完整 URL
$a.attr('data-role'); // "admin" (字符串)
$a.data('role'); // "admin" (自動類型轉換,緩存)
$a.prop('href'); // 完整 URL (property)
// 區別:
// - attr: 操作 HTML 屬性 (attribute)
// - prop: 操作 DOM 屬性 (property),如 checked, disabled, selected, value
// - data: 讀取 data-* 並嘗試 JSON 解析,寫入只存在 jQuery 緩存不修改 DOM
$('.menu').on('click', '.menulink > a', function (e) {
e.preventDefault();
var $this = $(this); // 當前點擊的
var $li = $this.parent(); // 父級
var $span = $this.children('span'); // 子級
var $ul = $this.closest('ul.menu'); // 最近祖先
console.log('當前 a id:', this.id);
console.log('父 li class:', $li.attr('class'));
console.log('子 span 文本:', $span.text());
console.log('祖先 ul id:', $ul.attr('id'));
});
this.id、this.href、this.className 無 jQuery 封裝開銷var $this = $(this); 緩存$('.menulink > a') (子選擇器) 比 $('.menulink a') (後代選擇器) 快jQuery 獲取節點屬性的核心在於「選對元素、用對方法」:
- 選元素:子選擇器 >、後代選擇器 、.children()/.find()/.parent()/.closest()
- 取值:原生 this.prop 最快 → .prop() 處理布爾屬性 → .attr() 處理 HTML 屬性 → .data() 處理 data-* 並自動解析
- 批量:.map(fn).get() 產出原生數組,避免 jQuery 對象開銷