在 jQuery 選擇器鏈中,filter() 與 find() 是兩個極易混淆卻用途截然不同的方法。一句話總結核心差異:find() 向下查找「後代元素」,filter() 向內篩選「自身集合」。本文將透過參數類型、DOM 遍歷方向、多條件邏輯、函式回調等維度,徹底釐清兩者邊界。
// 從所有 中篩選出 class 含 external 的
$('a').filter('.external');
$('a').filter(function(index) {
// this 指向當前 DOM 元素
// 返回 true 保留,false 剔除
return $(this).hasClass('external');
});
進階:函式接收 index 參數,可實現「奇偶行」、「每第 N 個」等邏輯。
| 維度 | find() | filter() |
|---|---|---|
| 遍歷方向 | 向下:當前集合的後代元素(子、孫、曾孫...) | 向內:當前集合自身元素 |
| 參數類型 | 單一選擇器字串 | 選擇器字串、函式、jQuery 物件、DOM 元素 |
| 多條件邏輯 | 不支援多選擇器(需用 find('a, b') 群組選擇器) | 支援逗號分隔 filter('.first, .last') 邏輯 OR |
| 函式回調 | 不支援 | 支援,自動傳入 index,需返回 boolean |
| 典型用例 | $('#form').find('input') 找表單內所有輸入框 | $('div').filter('.active') 篩選出 active 的 div |
| 記憶口訣 | Find = 找孩子(向下) | Filter = 篩自己(向內) |
<div class="first">first content<span class="test">test content</span></div>
<div class="last">last<span class="test">last test content</span></div>
<div class="last">last<span>last no test content</span></div>
$('div').find('.test').html();
// 返回第一個 div 內 .test 的 HTML:'test content'
// 找到所有 div 內部的 .test 元素(共 2 個)
$('div').filter('.test').html();
// 返回 undefined 或報錯
// 因為 div 本身沒有 .test class,篩選結果為空集合
$('div').filter('.first, .last').html();
// 返回第一個符合條件 div 的 HTML:'first content...'
// 選中 class 為 first 或 last 的 div(共 3 個)
$('div').filter(function(index) {
// 只保留包含 .test 子元素的 div
return $(this).find('.test').length > 0;
}).css('border', '2px solid red');
$('#parent').filter('.child') 永遠不會找到子元素,除非 #parent 本身也有 .child class。請改用 find() 或 children()。
// 先找容器,再篩選容器,最後找容器內的目標
$('.container').filter('.active').find('.item').show();
find() 使用瀏覽器原生 querySelectorAll(現代瀏覽器),速度極快。filter() 需遍歷現有集合並逐一測試,集合較大時較慢。$('#scope').find() 優於 $('*').filter())。記住 「Find 向下找後代,Filter 向內篩自己」 這一核心法則,配合 filter() 強大的函式回調與多條件支援,你就能精準掌控任何複雜的 DOM 選擇場景。下次寫選擇器鏈時,先問自己:「我要找孩子,還是要篩選自己?」