jQuery选择器之基本筛选选择器
很多时候我们不能直接通过基本选择器与层级选择器找到我们想要的元素,为此jQuery提供了一系列的筛选选择器用来更快捷的找到所需的DOM元素。筛选选择器很多都不是CSS的规范,而是jQuery自己为了开发者的便利延展出来的选择器
1、筛选选择器
筛选选择器的用法与CSS中的伪元素相似,选择器用冒号“:”开头,通过一个列表,看看基本筛选器的描述:
2、注意事项:
:eq(), :lt(), :gt(), :even, :odd 用来筛选他们前面的匹配表达式的集合元素,根据之前匹配的元素在进一步筛选,注意jQuery合集都是从0开始索引
gt是一个段落筛选,从指定索引的下一个开始,gt(1) 实际从2开始
3、示例代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>基本筛选选择器</title>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
<style>
.left {
width: auto;
height: 120px;
}
.left div {
width: 70px;
height: 70px;
padding: 5px;
margin: 5px;
float: left;
background: #bbffaa;
border: 1px solid #ccc;
}
.bottom {
width: 800px;
}
.bottom div,
.bottom span {
display: block;
width: 80px;
height: 80px;
margin: 5px;
background: #bbffaa;
float: left;
font-size: 14px;
}
.bottom .small {
width: 60px;
height: 25px;
font-size: 12px;
background: #fab;
}
</style>
</head>
<body>
<h2>基本筛选器</h2>
<h3>:first/:last/:even/:odd</h3>
<div class="left">
<div class="div">
<p>div:first</p>
<p>:even</p>
</div>
<div class="div">
<p>:odd</p>
</div>
<div class="div">
<p>:even</p>
</div>
<div class="div">
<p>:odd</p>
</div>
<div class="div">
<p>:even</p>
</div>
<div class="div">
<p>div:last</p>
<p>:odd</p>
</div>
</div>
<script type="text/javascript">
//找到第一个div
$('.div:first').css("color", "#CD00CD");
</script>
<script type="text/javascript">
//找到最后一个div
$('.div:last').css("color", "#CD00CD");
</script>
<script type="text/javascript">
//:even 选择所引值为偶数的元素,从 0 开始计数
$('.div:even').css("border", "3px groove red");
</script>
<script type="text/javascript">
//:odd 选择所引值为奇数的元素,从 0 开始计数
$('.div:odd').css("border", "3px groove blue");
</script>
<h3>:eq/:gt/:lt</h3>
<div class="left">
<div class="aaron">
<p>:lt(3) and :eq(0)</p>
</div>
<div class="aaron">
<p>:lt(3) and :eq(1)</p>
</div>
<div class="aaron">
<p>:lt(3) and :eq(2)</p>
</div>
<div class="aaron">
<p>:eq(3)</p>
</div>
<div class="aaron">
<p>:gt(3) and :eq(4)</p>
</div>
<div class="aaron">
<p>:gt(3) and :eq(5)</p>
</div>
</div>
<script type="text/javascript">
//:eq
//选择单个
$('.aaron:eq(2)').css("border", "3px groove blue");
</script>
<script type="text/javascript">
//:gt 选择匹配集合中所有索引值大于给定index参数的元素
$('.aaron:eq(3)').css("border", "3px groove green");
</script>
<script type="text/javascript">
//:gt 选择匹配集合中所有索引值大于给定index参数的元素
$('.aaron:gt(3)').css("border", "3px groove red");
</script>
<script type="text/javascript">
//:lt 选择匹配集合中所有索引值小于给定index参数的元素
//与:gt相反
$('.aaron:lt(3)').css("color", "red");
</script>
<h3>:not</h3>
<div class="left">
<div>
<input type="checkbox" name="a" />
<p>Aaron</p>
</div>
<div>
<input type="checkbox" name="b" />
<p>数据</p>
</div>
<div>
<input type="checkbox" name="c" checked="checked" />
<p>其他</p>
</div>
</div>
<script type="text/javascript">
//:not 选择所有元素去除不匹配给定的选择器的元素
//选中所有紧接着没有checked属性的input元素后的p元素,赋予颜色
$('input:not(:checked) + p').css("background-color", "#CD00CD");
</script>
</body>
</html>