一、 .filter(selector)
这种用法是在已匹配的元素中按照给定的selector参数(jquery选择器表达式)进行筛选,然后将匹配的元素包装成jquery元素集合返回。这个方法是用来缩小匹配范围的,selector参数可以是多个表达式用逗号连接起来。来看例子:
HTML代码:
- 11111
- 22222
- 33333
- 44444
- 55555
- 66666
- 77777
Jquery代码:$("ul>li").filter(":even").css("color","red");
//将索引为偶数的li背景变为红色
上面的jquery代码和下面的jquery代码效果是一样的$("ul>li:even").css("color","red");
//将索引为偶数的li背景变为红色
再来看一下选择器表达式用逗号连接起来的用法:$("ul>li").filter(":even,.item").css("color","blue");
//将索引为偶数和calss为item的li背景变为蓝色
demo示例如下:
- 11111
- 22222
- 33333
- 44444
- 55555
- 66666
- 77777
$(function(){
$("#test1").click(function(){
$("ul>li").filter(":even").css("color","red");//将索引为偶数的li背景变为红色
//这个式子和 $("ul>li:even").css("color","red"); 等效
});
$("#test2").click(function(){
$("ul>li").filter(":even,.item").css("color","blue");//将索引为偶数和calss为item的li背景变为蓝色
});
});
二、 .filter( function(index) )
这种使用方法是对匹配的元素进行遍历,如果function(index)返回的值为true的话,那么这个元素就被选中,如果返回值为false的话,那么这个元素就不被选中
index参数是当前的匹配元素在原来的元素集合中的索引。下面的例子:
HTML代码:
jquery代码:$("p").filter(function(index) {
return index == 1 || $(this).attr("id") == "fourth";
}).css("border", "5px double blue");
上面代码的结果是 第二个p元素和 id为“fourth”的p元素的边框变成了双线颜色为蓝色
demo示例如下:
p{ width:60px; height:60px; margin:5px; float:left;border:3px white solid;background:#ff0000 }
$("#test").click(function(){
$("p").filter(function(index) {
return index == 1 || $(this).attr("id") == "fourth";
}).css("border", "5px double blue");
});
三、 .filter( element )
element参数为DOM对象,如果element DOM对象和匹配的元素是同一个元素的话,那么这个元素会被匹配。
看例子吧:
还是对上面的HTML代码,看jquery代码:$("p").filter(document.getElementById("third")).css("border", "5px double blue");
结果是id为third的p元素边框有变化。$("#third").css("border", "5px double blue");
demo示例如下:
p{ width:60px; height:60px; margin:5px; float:left;border:3px white solid;background:#ff0000 }
$("#test").click(function(){
$("p").filter(document.getElementById("third")).css("border", "5px double blue");
});
四、 .filter(jQuery object)
这个用法和上面的.filter( element )的用法差不多,只是一个参数为DOM对象,一个参数为jquery对象。
看例子:
同样是对上面的HTML代码,看jquery代码:$("p").filter($("#third")).css("border", "5px double blue");
结果是id为third的p元素边框有变化。
同样直接用下面的jquery代码会更好:$("#third").css("border", "5px double blue");
demo示例如下:
p{ width:60px; height:60px; margin:5px; float:left;border:3px white solid;background:#ff0000 }
$("#test").click(function(){
$("p").filter($("#third")).css("border", "5px double blue");
});