jquery中filter的使用



一、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>




文章转载自:  jquery filter方法    http://www.studyofnet.com/news/951.html


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值