.filter()
描述: 筛选元素集合中匹配表达式 或 通过传递函数测试的 那些元素集合。
.filter(selector)
selector
类型:
Selector
一个用于匹配元素的选择器字符串。
.filter(function(index))
function(index)
类型:
Function()
一个函数用作测试集合中的每个元素。
this
是当前DOM元素。
.filter(element)
element
类型:
Element
一个匹配当前元素集合的元素。
.filter(jQuery object)
jQuery object
类型:
Object
现有jQuery对象,用于进一步筛选当前元素集合。
如果一个jQuery对象表示一个DOM元素的集合,.filter()
方法构造了一个新的jQuery对象的子集。所提供的选择器是对每个元素进行测试;这个选择器匹配的所有元素将包含在结果中。
例子:
Example: 改变所有 div 的颜色,然后为含有 "middle" 样式的 div 添加边框。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js"></script>
<style>
div { width:60px; height:60px; margin:5px; float:left;
border:2px white solid;}
</style>
</head>
<body>
<div></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div class="middle"></div>
<div></div>
<script>
$("div").css("background","#c8ebcc").filter(".middle").css("border-color","red");
</script>
</body>
</html>
效果图:
Example: C改变所有 div 的颜色,然后为第二个 div (index == 1) 及 id 为 "fourth" 的 div 添加边框。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script src="jquery-1.10.2.js"></script>
<style>
div { width:60px; height:60px; margin:5px; float:left;
border:2px white solid;}
</style>
</head>
<body>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
<div id="fourth"></div>
<div id="fifth"></div>
<div id="sixth"></div>
<script>
$("div").css("background","#b4b0da").filter(function(index) {
return index == 1 || $(this).attr("id") == "fourth";
}).css("border","3px double red");
</script>
</body>
</html>
效果图:
Example: 选择所有的 div,并使用 DOM 元素进行筛选,过滤出 id 为 "unique" 的元素。
1
|
|
Example: 选择所有的 div,并使用 jQuery 对象进行筛选,过滤出 id 为 "unique" 的元素。
1
|
|