DIV CSS 佈局教程網

jQuery 中 filter 方法用法及與 find 的區別
編輯:JavaScript綜合知識     

filter() 是 jQuery 中非常實用的篩選方法,它能將匹配的元素集合縮減為符合指定條件的元素。本文將介紹 filter 的兩種參數形式,並重點對比它與 find 方法的關鍵差異。

filter 的兩種參數類型

1. 傳遞選擇器:

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

2. 傳遞過濾函數:

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

filter 與 find 的區別

  • find() 會在元素內部尋找符合條件的「子元素」。
  • filter() 則是篩選「當前集合」中符合條件的元素,屬於同層過濾。
  • find 函數是在當前物件集合的子元素中進行查詢。
  • filter 函數是對當前物件集合進行過濾,利用條件縮小範圍。
  • find 的參數是 jQuery 選擇器表達式。
  • filter 的參數也是選擇器表達式,但可有多個條件(用逗號分隔,表「或」關係)。
  • filter 的參數也可以是函數,呼叫時會自動傳入 index 參數,函數需返回 true 或 false 來選中或排除元素。

完整示例

<!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 程式設計有所幫助。

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