DIV CSS 佈局教程網

搞懂 jQuery filter():參數形式與 find() 的差別
編輯:JQuery特效代碼     

filter() 是把玩 jQuery 選取結果時一定會用到的方法,但它和 find() 經常被搞混。這篇把兩者的定位講清楚。

filter() 做什麼

filter() 會把目前的元素集合縮小,只保留符合條件的元素。也就是說,它是在「現有的這一批」裡面做篩選,不會往下找子元素。

參數有兩種常見寫法:

1. 傳入選擇器字串

$('a').filter('.external')

2. 傳入過濾函式

$('a').filter(function (index) {
    return $(this).hasClass('external');
})

find() 與 filter() 的差別

一句話概括:find() 是往下找子元素,filter() 是在同一層裡篩選。

  • find() 會在選到的元素內部繼續尋找符合條件的後代元素。
  • filter() 只是把目前這批元素依條件過濾一遍,範圍只會變小。
  • find() 的參數是 jQuery 選擇器表達式。
  • filter() 的參數除了選擇器表達式,也可以是一個函式;函式會自動收到 index,回傳 true 表示保留、false 表示排除。
  • filter() 支援多個條件以逗號分隔,彼此是「或」的關係。

對照範例

<!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 的差異會非常直觀:btn1 找的是 div 裡面的 .test,btn2 找的是 div 本身有沒有 .test(沒有,所以是空),btn3 是筛出 .last 的 div,btn4 則示範多條件。

希望這篇對大家的 jQuery 開發有幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved