欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jQuery遍历 - 过滤first(),last()和eq()使用

程序员文章站 2022-03-23 13:44:27
jQuery遍历 - 过滤最基本的过滤方法是first(),last()和eq(),它们允许您根据元素在一组元素中的位置选择特定元素。 其他过滤方法(如filter()和not())允许您选择与特定条件匹配或不匹配的元素。 jQuery first()方法first()方法返回指定元素的第一个元素。 ......

jquery遍历 - 过滤
最基本的过滤方法是first(),last()和eq(),它们允许您根据元素在一组元素中的位置选择特定元素。

其他过滤方法(如filter()和not())允许您选择与特定条件匹配或不匹配的元素。

jquery first()方法
first()方法返回指定元素的第一个元素。

以下示例选择第一个<div>元素:

<!doctype html>
<html>
<meta charset="utf-8">
<title>jq</title>
<head>
//引用自己的jq库路径
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function () {
$("div p").first().css("background-color", "red");
});
</script>
</head>
<body>
<h1>欢迎访问jq教程</h1>
<div>
<p>这是 div 中的第一个p段落。</p>
</div>
<div>
<p>这是 div 中的最后一个p段落。</p>
</div>
<p>这是一个p段落。</p>
</body>

</html>
jquery last()方法
last()方法返回指定元素的最后一个元素。
以下示例选择最后一个<div>元素:
<!doctype html>
<html>
<meta charset="utf-8">
<title>jq</title>
<head>
//引用自己的jq库路径
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function () {
    $("div p").last().css("background-color", "red");
});
</script>
</head>
<body>
<h1>欢迎访问jq教程</h1>
<div>
<p>这是 div 中的第一个p段落。</p>
</div>
<div>
<p>这是 div 中的最后一个p段落。</p>
</div>
<p>这是一个p段落。</p>
</body>

</html>

 

jquery eq()方法
eq()方法返回具有所选元素的特定索引号的元素。

索引号从0开始,因此第一个元素的索引号为0而不是1.以下示例选择第二个<p>元素(索引号1):

<!doctype html>
<html>
<meta charset="utf-8">
<title>jq</title>
<head>
//引用自己的jq库路径
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function () {
    $("p").eq(1).css("background-color", "red");
});
</script>
</head>
<body>
<h1>欢迎访问jq教程</h1>
<p>jq教程 (index 0).</p>
<p>https://www.jc2182.com (index 1)。</p>
<p>google (index 2).</p>
<p>http://www.google.com (index 3)。</p>
</body>
</html>

jquery filter() 和 jquery not()方法