jQuery中的filter和find函数

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代码:

1
2
3
4
5
6
7
8
<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代码:

1
2
3
4
5
6
7
8
<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()方法在指定元素中查找符合条件的子元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<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>

posted on 2013-01-15 15:50  Paul_bai  阅读(619)  评论(0编辑  收藏  举报

导航