Jquery filter 函数是用来从一系列匹配的元素中提出自己的元素。
1 filter(selector)
在一系列的匹配元素中,仅获得filter()选择器匹配的。
例如:
$("div").filter("#div1").css('background-color', 'blue');
从所有匹配的div元素中提出其id为#div1的元素,并把其背景颜色设置为blue。
2 filter(function)
从一系列的匹配元素中,获得通过function测试的元素。函数的内部传递了一个索引,它代表了匹配元素的索引,此索引是从0开始的。
例如:
$('div').filter(function(index) {
if(index==2 || index==3){ //0 index based
return true;
}
}).css('background-color', 'blue');
匹配所有的div元素,filter函数仅选择匹配的div元素集中的第2个和第3个div。
$('div').filter(function(index) {
return $("b", this).length == 1;
}).css('background-color', 'blue');
Matched all the div elements,filter with function to select the div element which contains <b> tag.
从所有匹配的div元素中,选择出包含b标签的的div标签。
具体实例:
<html>
<head>
<title>jquery filter example</title>
<script type="text/javascript" src="../jquery-1.11.1.min.js"></script>
</head>
<body>
<h1>jquery filter example</h1>
<script type="text/javascript">
$(document).ready(function(){
$("#filterSelector").click(function(){
$("div").css('background-color','white');
$("div").filter("#div1").css('background-color','blue');
});
$("#filterFunction").click(function(){
$('div').css('background-color','white');
$('div').filter(function(index){
if(index==2||index==3){
return true;
}
}).css('background-color','blue');
});
$('#filterFunction2').click(function(){
$('div').css('background-color','white');
$('div').filter(function(){
return $("b",this).length==1;
}).css('background-color','blue');
});
});
</script>
<div id="div1">
<b>this is div1 with b tag</b>
</div>
<div id="div2">
this is div2
</div>
<div id="div3">
<b> this is div3 with b tag</b>
</div>
<div id="div4">this is div4</div>
<br/>
<br/>
<br/>
<input type="button" value='filter(selector)' id="filterSelector">
<input type="button" value='filter(index)' id='filterFunction'>
<input type="button" value='filter(index)+b' id='filterFunction2'>
</body>
</html>
效果:
点击按钮1:
点击按钮2:
点击按钮3: