<!DOCTYPE html>
<html>
<head>
<title>jquery的过滤器使用</title>
<meta charset="utf-8"/>
<style type="text/css">
div{width:100px;height: 100px;float: left;margin: 2px;background: greenyellow;}
.blue{background: blue;}
.red{background: red}
.green{background: green}
.pos{background:pink; }
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
/**
* jquery的过滤器
* 1.eq(index) 获取第N个元素
* 2.hasClass(class) 是否存在某个特定的类
* 3.filter(express) 帅选出与指定表达式匹配的元素集合
* 4.filter(fn) 筛选出与指定函数返回值匹配的元素集合
* 5.is(express) 用一个表达式来检查当前选择的元素集合
* 6.map(callback) 将一组元素转换成其他数组
* 7.has(express) 保留包含特定后代的元素,去掉那些不含指定后台的元素
* 8.not(express) 删除与指定表达式匹配的元素
* 9.slice(start,[end]) 选取一个匹配的子集
*/
$(function(){
//hasClass(class) 我们通过筛选某个div是否具有某个指定的类,来该改变它的颜色
$("div").click(function(){
if($(this).hasClass("red"))
$(this).css("background","blue");
});
//下标过滤eq(index)数组下标为3的div元素背景色为红色
$("div").eq(3).css("background","red");
//filter(express)表达式过滤,凡是存在red类的div元素都为黄色
$("div").filter(".red").click(function(){
$(this).css("background","yellow");
});
$("div").filter(".red,.pos").click(function(){
$(this).css("background","yellow");
});
//filter(function)函数表达式
$("div").filter(function(index){
//当div含有梁哥子元素的时候,会将该div的背景颜色变为yellow
return $("span",this).length==2;
}).css("background","yellow");
//has(express) 保留包含特定后代的元素,去掉那些不含指定后台的元素
//当div没有span子元素的时候,会改变它的背景颜色
$("div").has("span").css("background","yellow");
//is(express)用一个表达式来检查当前选择的元素集合
//判断某个指定id的父元素是否是div
if($("#felayman").parent().is("div")){
//alert("id为felayman的元素的父元素是div");
}else{
// alert("id为felayman的元素的父元素不是div");
}
//map(callback)将一组元素转换成其他数组
//遍历所有a标签里的内容
//这里的$arr是jquery变量,本身是一个javascript变量的数组
var $arr = $("a").map(function(){
return $(this).text();
});
//将jquery对象转化成javascript变量
var arr1 = $arr.get();//默认以','为数组分隔符
var arr1 = $arr.get().join("-");//以'-'为数组分隔符
//alert(arr1);
//not(express)删除所有不是指定类型的元素
//所有不含id为span的span元素都隐藏起来
$("span").not("#span").hide();
//slice(start,[end])选取一个匹配的子集
//将序号为2-5之间的a标签的内容的颜色变为blue
$("a").slice(2,5).css("color","blue");
});
</script>
</head>
<body>
<a>1</a>
<a>2</a>
<a>3</a>
<a>4</a>
<a>5</a>
<br/>
<div class="blue">
<span id="felayman">hello</span>
</div>
<div class="red">
<span>hello1</span>
<span>hello2</span>
</div>
<div class="green">
<span>hello1</span>
<span>hello2</span>
<span>hello3</span>
</div>
<div class="red pos"></div>
</body>
</html>