一、filter()语法


$(selector).filter(criteria,function(index))


参数

描述

criteria

可选。规定要从被选元素组合中返回的选择器表达式、jQuery 对象、一个或多个元素。


提示:如需规定多个条件,请使用逗号分隔。

function(index)

可选。为集合中的每个元素规定要运行的函数。如果返回 true,则保留元素,否则元素将被移除。


  • index - 集合中元素的 index 位置。

注意:this 是当前的 DOM 元素。

 



二、jquery中filter()实例

 

1、使用选择器表达式过滤


<ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li>
  <li>list item 4</li>
  <li>list item 5</li>
  <li>list item 6</li>
</ul>


<script>
$('li').filter(':even').css('background-color', 'red');
</script>



2、使用多个条件过滤


<script>
$(document).ready(function(){
  $("p").filter(".intro,#outro").css("background-color","yellow");
});
</script>

<h1>Welcome to My Homepage</h1>
<p>My name is Donald.</p>
<p class="intro">I live in Duckburg.</p>
<p id="outro">I love Duckburg.</p>
<p>My best friend is Mickey.</p>



3、使用 jQuery 对象过滤


<script>
$(document).ready(function(){
 $("p").filter($("div p.intro")).css("background-color","yellow");
});
</script>

<div style="border:1px solid black;">
This is a div element
<h1>Welcome to My Homepage</h1>
<p>My name is Donald.</p>
<p class="intro">I live in Duckburg (will be selected).</p>
<p>My best friend is Mickey.</p>
</div>

<p class="intro">This p element is outside the div element.</p>
<p>This p element is also outside the div element.</p>



4、使用过滤函数


可以接受一个函数作为参数,然后根据函数的返回值判断,如果返回值是true,这个元素将被保留,如果返回值是false,这个元素将被剔除。


<script>
$(document).ready(function(){
  $("p").filter(function(){  
    return $("span",this).length==2;}).css("background-color","yellow");
});
</script>

<div>
<p>A p element <span>with one span element.</span></p>
<p>A p element <span>with</span> two <span>span elements.</span></p>
<p>A p element <span>with one span element.</span></p>
<p>A p element <span>with</span> two <span>span elements.</span></p>
<p>A p element with no span element.</p>
</div>

<p>This example returns all p elements that have two span elements. P elements with none, one, or more than two span elements, will not be returned.</p>