jquery中filter方法用法实例分析
本文实例讲述了jquery中filter方法用法。分享给大家供大家参考。具体分析如下:
filter()方法将匹配元素集合缩减为匹配指定选择器的元素。
filter方法中的参数可以为字符串值,包含供匹配当前元素集合的选择器表达式。
一、filter的参数类型可分为两种
1、传递选择器
$('a').filter('.external')
2、传递过滤函数
$('a').filter(function(index){
return$(this).hasClass('external');
})
二、Jquery中find与filter区别
1、find()会在div元素内寻找class为classname的元素。
2、filter()则是筛选div的class为classname的元素。
3、基本是find子元素找,filter是平级找
4、find函数是在当前对象集合的子元素中进行查询;
5、filter函数是对当前对象集合进行过滤,利用过滤条件缩小范围;
6、find函数的参数是jQuery选择器表达式;
7、filter的参数也是选择器表达式,但可以有多个条件,用逗号分隔(逻辑或关系);
8、filter的参数也可以是个函数,调用函数时会自动传入index参数,函数需返回true或false以选中或排除元素.
例如:
<!DOCTYPE>
<html>
<head>
<metahttp-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>
<inputtype="button"value="test-find"id="btn1"/>
<inputtype="button"value="test-filter"id="btn2"/>
<inputtype="button"value="test-filter"id="btn3"/>
<inputtype="button"value="test-filter"id="btn4"/>
<divclass="first">firstcontent<spanclass="test">testcontent</span></div>
<divclass="last">last<spanclass="test">lasttestcontent</span></div>
<divclass="last">last<span>lastnotestcontent</span></div>
</body>
</html>
希望本文所述对大家的jQuery程序设计有所帮助。