遍歷方法分類速查
| 方向 | 單個 (最近) | 全部 (所有) | 篩選器支援 |
| 祖先 | .parent() | .parents() / .parentsUntil() | ✅ |
| 後代 | - | .children() (直系) / .find() (所有層級) | ✅ |
| 同胞 (前) | .prev() | .prevAll() / .prevUntil() | ✅ |
| 同胞 (後) | .next() | .nextAll() / .nextUntil() | ✅ |
| 同胞 (雙向) | - | .siblings() | ✅ |
| 自身 | .addBack() | - | - |
完整互動範例
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery DOM 遍歷方法示範</title>
<style>
.container { max-width: 700px; margin: 40px auto; padding: 20px; font-family: sans-serif; }
.tree { border-left: 2px solid #1976d2; padding-left: 20px; margin-left: 10px; position: relative; }
.node { margin: 8px 0; padding: 8px 12px; background: #f5f5f5; border-radius: 4px; border: 1px solid #e0e0e0; position: relative; }
.node::before { content: ''; position: absolute; left: -22px; top: 50%; width: 14px; height: 2px; background: #1976d2; }
.node.highlight { background: #fff3e0; border-color: #ff9800; box-shadow: 0 0 0 2px #ff9800; }
.controls { margin: 20px 0; display: flex; gap: 8px; flex-wrap: wrap; }
button { padding: 8px 12px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; }
button.secondary { background: #757575; }
.result { background: #263238; color: #aed581; padding: 12px; border-radius: 4px; font-family: monospace; font-size: 13px; min-height: 40px; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container">
<h2>DOM 結構圖</h2>
<div class="tree">
<div id="div1" class="node">div1 (祖先)</div>
<div class="tree">
<input id="text1" type="text" value="input (文字節點間隔)" class="node" readonly style="border:none; background:#eee;">
<div id="div2" class="node"><strong>div2 (目標節點)</strong></div>
<input id="text2" type="text" value="input" class="node" readonly style="border:none; background:#eee;">
<div class="tree">
<div id="div3" class="node">div3 (div2 子代)</div>
<div id="div4" class="node">div4 (div2 子代)</div>
</div>
<input id="text3" type="text" value="input" class="node" readonly style="border:none; background:#eee;">
<div id="div5" class="node">div5 (div2 同胞)</div>
</div>
</div>
<div class="controls">
<button data-method="prev" data-args='["div"]'>.prev('div')</button>
<button data-method="prevAll" data-args='["div"]'>.prevAll('div')</button>
<button data-method="next" data-args='["div"]'>.next('div')</button>
<button data-method="nextAll" data-args='["div"]'>.nextAll('div')</button>
<button data-method="siblings" data-args='["div"]'>.siblings('div')</button>
<button data-method="siblings" data-args='[]' class="secondary">.siblings() (全部)</button>
<button data-method="parent" data-args='[]'>.parent()</button>
<button data-method="parents" data-args='["div"]'>.parents('div')</button>
<button data-method="children" data-args='["div"]'>.children('div')</button>
<button data-method="find" data-args='["div"]'>.find('div') (後代)</button>
<button id="btnClear" class="secondary">清除高亮</button>
</div>
<div class="result" id="result">點擊按鈕查看匹配元素 ID</div>
</div>
<script>
$(function() {
const $target = $('#div2');
const $result = $('#result');
$('button[data-method]').on('click', function() {
$('.node').removeClass('highlight');
const method = $(this).data('method');
const args = $(this).data('args') || [];
let $matched;
switch (method) {
case 'prev': case 'next': case 'parent': case 'children': case 'find': case 'siblings':
case 'prevAll': case 'nextAll': case 'parents':
$matched = $target[method](...args);
break;
}
if ($matched && $matched.length) {
$matched.addClass('highlight');
const ids = $matched.map((_, el) => el.id || el.tagName).get().join(', ');
$result.text(`匹配到 [${ids}] (共 ${$matched.length} 個)`);
} else {
$result.text('未匹配到任何元素');
}
});
$('#btnClear').on('click', () => {
$('.node').removeClass('highlight');
$result.text('已清除高亮');
});
});
</script>
</body>
</html>
核心方法深度解析
1. .prev() / .next() - 緊鄰同胞
- 只返回 緊鄰 的一個同胞元素
- 選擇器參數為 過濾器:先找緊鄰同胞,再判斷是否匹配選擇器
$('#div2').next('div'):若緊鄰的是 input,返回空集合 (不會繼續往後找)
2. .prevAll() / .nextAll() - 所有同胞
- 返回 所有 前/後 同胞元素
- 順序:
.prevAll() 返回 由近至遠 (倒序),.nextAll() 返回 由近至遠 (正序)
- 搭配選擇器過濾:
.prevAll('div') 只取 div 同胞
3. .siblings() - 雙向同胞
- 返回 前後所有 同胞元素 (不含自身)
- 順序:DOM 順序 (先前同胞,後後同胞)
- 最常用於「排他」操作:
$(this).addClass('active').siblings().removeClass('active')
4. .children() vs .find() 關鍵差異
| 方法 | 遍歷深度 | 返回順序 | 效能 |
.children(selector) | 僅 直系子元素 (單層) | DOM 順序 | 極快 |
.find(selector) | 所有 後代元素 (遞迴) | DOM 順序 | 較慢 (需遞迴) |
<div id="parent">
<span><b>孫子</b></span> <!-- children 不包含,find 包含 -->
<p>兒子</p> <!-- 兩者都包含 -->
</div>
$('#parent').children() // [p]
$('#parent').find('*') // [span, b, p]
5. .parents() vs .closest()
.parents('selector'):返回 所有匹配的祖先 (由近至遠)
.closest('selector'):返回 第一個匹配的祖先 (含自身檢查),效能更好
// 事件委派中獲取最近的列表項
$('.item').on('click', '.btn-del', function() {
const $item = $(this).closest('.item'); // ✅ 推薦
// const $item = $(this).parents('.item').first(); // 同效果但較慢
});
鏈式遍歷與 .end() / .addBack()
// 經典鏈式:找到父容器 -> 找所有按鈕 -> 綁定事件 -> 返回父容器繼續操作
$('#form')
.find('.btn-group')
.children('button')
.on('click', handler)
.end() // 返回 .btn-group
.end(); // 返回 #form
// .addBack() 將「上一個選擇集合」合併到當前集合
$('div').find('p').addBack() // 選中 div 及其內部所有 p
效能優化建議
- 優先用
.children() 代替 .find() 當只需直系子元素
- 快取選擇結果:避免在迴圈/高頻事件中重複遍歷
- 事件委派替代遍歷綁定:
$parent.on('click', '.child', handler) 替代 $parent.find('.child').on('click', handler)
- 大量元素用原生 API:
element.children, element.parentElement, element.nextElementSibling
總結
jQuery 遍歷方法提供了豐富的 DOM 導航能力。核心原則:明確方向、善用篩選器、理解返回順序、優先用 children/closest。現代開發中,簡單遍歷優先用原生 DOM API (parentElement, children, closest),複雜邏輯才引入 jQuery。