您的位置:首页 > Web前端 > JQuery

jQuery中find()方法和filter()方法的区别

2013-09-04 17:47 836 查看
jQuery官方的API这样说明filterfind函数:

filter(selector):
Description: Reduce the set of matched elements to those that match the selector or pass the function’s test.

find(selector):
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector.
find()会在当前指定元素中查找符合条件的子元素,是对它的子集操作,而filter()则是在当前指定的元素集合中查找符合条件的元素,是对自身集合元素进行筛选。

看下边的例子就会一目了然:

HTML代码:
<div class="benben">
<p>Hello,World!</p>
<p>Hello,World Again!</p>
<p class="test">Test1</p>
</div>
<div class="test">
<p>Test2</p>
</div>

jQuery代码:
<script type="text/javascript">
//using find()
var $find=$("div").find(".test");
alert($find.html());//display "Test1"
//using test()
var $filter=$("div").filter(".test");
alert($filter.html());//display "Test2"
</script>

很多时候经常用到find()或者filter(),下边的代码中就用到了find()方法在指定元素中查找符合条件的子元素。
<script type="text/javascript">
$(document).ready(function() {
//mouse hover
$("ul.test>li").hover(function() {
$(this).find("a:first").css({
"background":"white",
"position":"relative"
});
},
//mouse out
function(){
$(this).find("a:first").css({
"background":"",
"position":""
});
});
});
</script>

参考:http://www.benben.cc/blog/?p=352
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: