php遍历dom节点,filter()方法遍历DOM节点操作用法详解

一、 .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");

});

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值