jQuery除了next、prev这类遍历方法,还提供位置筛选选择器,可以选取第一个、最后一个、反向、奇数、偶数等元素。
- 选取第一个元素
:first$("div:first")选取第一个<div>$(".main:first")选取class为main的第一个元素 - 选取最后一个元素
:last$("div:last")选取最后一个<div> - 取反选择器
:not()$("input:not(.green)")选取class不是green的<input> - 奇偶选择器
:even、:odd选取索引为偶数、奇数的元素;$("input:even")选取索引为偶数的<input>注意:索引从0开始 - 索引选择器
:eq(索引)、:gt(索引)、:lt(索引),分别选取索引等于、大于、小于该序号的元素。 例:$("input:lt(5)")选取索引小于5的<input>使用$("input").length可以获取匹配元素总数量 - 其他选择器
$(":header")选取所有h1~h6标题元素$("div:animated")选取正在执行动画的<div>元素
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm13.aspx.cs" Inherits="WebApplication1.WebForm13" %>
<!DOCTYPE html>
<html xmlns="[http://www.w3.org/1999/xhtml](http://www.w3.org/1999/xhtml)">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="[http://libs.baidu.com/jquery/1.8.3/jquery.min.js](http://libs.baidu.com/jquery/1.8.3/jquery.min.js)"></script>
<script type="text/javascript">
function deal() {
//alert($("div:first").text());
//alert($("div:last").text());
//alert($("input:not(.green)").val());
//alert($("div:odd").text());
//alert($("div:eq(4)").text());
alert($("div:lt(4)").text());
}
</script>
</head>
<body>
<div>鹿鼎记</div>
<div>算死草</div>
<div>大话西游</div>
<div>国产凌凌漆</div>
<div>功夫</div>
<input type="text" class="green" />
<input type="text" class="green" />
<input type="text" class="blue" />
<input type="text" class="green" />
<input type="text" class="green" />
<input type="button" onclick="deal()" value="执行" />
</body>
</html>
Code language: HTML, XML (xml)
说明:点击执行按钮,弹出索引小于4的所有div文本。
Previous: 了解一下jQuery的链式编程