一句話記法:find() 往「下一代以後」找,filter() 在「自己這一群」裡篩。
例如 $('div').find('.classname') 是到 div 的子元素裡找 class 為 classname 的節點;$('div').filter('.classname') 則是從選到的 div 之中,只留下 class 為 classname 的那些。
find 是在目前物件的子元素中查詢。filter 是對目前物件本身做過濾,用條件縮小範圍。find 的參數是 jQuery 選擇器運算式。filter 的參數除了選擇器運算式(可用逗號代表「或」),也可以是一個函式;函式會收到 index 參數,回傳 true 保留、false 排除。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(function() {
$('#btn1').click(function() { alert($('div').find('.test').html()); });
$('#btn2').click(function() { alert($('div').filter('.test').html()); });
$('#btn3').click(function() { alert($('div').filter('.last').html()); });
$('#btn4').click(function() { alert($('div').filter('.first,.last').html()); });
});
</script>
</head>
<body>
<input type="button" value="test-find" id="btn1" />
<input type="button" value="test-filter" id="btn2" />
<input type="button" value="test-filter" id="btn3" />
<input type="button" value="test-filter" id="btn4" />
<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>
</body>
</html>
$("p").filter(function(index) {
return $(this).hasClass("aa"); // 只保留 class 含 aa 的段落
}).text("被選到的內容");
補充一個常見誤解:filter('.first,.last') 中的逗號是「或」,會同時保留兩類;而 filter('.first').filter('.last') 才是連續套用兩個條件(交集)。