filter() 是 jQuery 中非常實用的篩選方法,它能將匹配的元素集合縮減為符合指定條件的元素。本文將介紹 filter 的兩種參數形式,並重點對比它與 find 方法的關鍵差異。
1. 傳遞選擇器:
$('a').filter('.external')
2. 傳遞過濾函數:
$('a').filter(function(index) {
return $(this).hasClass('external');
})
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>Document</title>
<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>
簡單來說:find 是「向下找子孫」,filter 是「就地篩選自己」。理解這個差異,就能在 DOM 操作時選對工具。希望本文能對你的 jQuery 程式設計有所幫助。