| 類別 | 方法 | 描述 | 返回值 |
|---|---|---|---|
| 篩選 | .eq(index) | 獲取指定索引元素(0 基礎,負數倒序) | jQuery |
.first() / .last() | 獲取首/尾元素 | jQuery | |
.filter(selector|fn) | 篩選匹配選擇器或函數返回 true 的元素 | jQuery | |
.not(selector|fn|element) | 排除匹配元素 | jQuery | |
.slice(start, end) | 截取索引範圍子集 [start, end) | jQuery | |
.is(selector) | 檢測是否至少一個匹配,返回 Boolean | Boolean | |
.map(callback) | 遍歷生成新 jQuery 對象(回調返回值組成) | jQuery | |
| 樹狀查找 | .children([selector]) | 獲取**直接子元素**(不含文本節點) | jQuery |
.find(selector) | 獲取**所有後代**元素 | jQuery | |
.parent([selector]) | 獲取直接父元素 | jQuery | |
.parents([selector]) | 獲取所有祖先元素(至 document) | jQuery | |
.parentsUntil(selector|element) | 獲取祖先直到匹配選擇器為止 | jQuery | |
.closest(selector) | 從自身向上查找**最近**匹配祖先(含自身) | jQuery | |
.siblings([selector]) | 獲取所有同輩元素(不含自身) | jQuery | |
| 同輩導航 | .next([selector]) | 緊鄰的下一個同輩 | jQuery |
.nextAll([selector]) | 之後所有同輩 | jQuery | |
.nextUntil(selector) | 之後同輩直到匹配為止 | jQuery | |
.prev([selector]) | 緊鄰的上一個同輩 | jQuery | |
.prevAll([selector]) | 之前所有同輩 | jQuery | |
.prevUntil(selector) | 之前同輩直到匹配為止 | jQuery | |
| 其他 | .add(selector|html|elements) | 將元素添加到當前集合 | jQuery |
.addBack() | 加入前一次操作前的集合(舊版 .andSelf()) | jQuery | |
.contents() | 獲取子節點(含文本、註釋節點) | jQuery | |
.each(fn) | 遍歷執行函數,`this` 指向 DOM 元素 | jQuery (鏈式) | |
.end() | 回退到上一個篩選狀態(鏈式核心) | jQuery | |
.offsetParent() | 獲取最近的定位父元素 | jQuery |
.end() 核心機制jQuery 內部維護一個**堆棧**,每次篩選/查找操作將新集合壓棧,`.end()` 彈棧回退。
$('#container')
.find('ul') // 壓棧:ul 集合
.children('li') // 壓棧:li 集合
.filter('.active')// 壓棧:active li
.addClass('on')
.end() // 回退到 li 集合
.end() // 回退到 ul 集合
.end(); // 回退到 #container
.each() 深度用法$('.item').each(function(index, element) {
// this === element (原生 DOM)
// index: 0-based
console.log(index, this.id, $(this).text());
// 返回 false 打斷循環,返回 true 繼續(相當於 continue)
});
$.each)// 數組
$.each([1,2,3], (i, val) => console.log(i, val)); // 0 1, 1 2, 2 3
// 對象
$.each({a:1, b:2}, (key, val) => console.log(key, val)); // a 1, b 2
// 二維數組
$.each([[1,4],[5,6]], (i, arr) => console.log(arr[0])); // 1, 5
.map() vs .each() 選型指南// 需要收集返回值形成數組/集合 → 用 .map()
const ids = $(':checkbox').map(function() { return this.id; }).get(); // 真數組
const idStr = ids.join(',');
// 只需副作用(修改 DOM、綁定事件、打印) → 用 .each()
$('li').each(function() { $(this).prepend('★ '); });