Jquery教程
Jquery动效
Jquery HTML/CSS
Jquery 事件
jquery常用

Jquery eq()方法

jQuery中的 eq()方法返回具有给定索引的元素。此方法将元素集减少为具有特定索引的元素集。索引可以是正数或负数。如果我们使用负索引,则索引计数从所选元素列表的末尾开始。
假设我们有一个表示元素集的jQuery对象,因此 eq()方法构造一个新的 JQuery 对象,其中包含该集合的一个元素。

语法

$(selector).eq(index)
此方法接受名为 index 的单个参数。索引是一个以 0 开头的整数。
index: 这是用于指定元素索引的必需参数。可以指定为正数或负数。负索引使索引计数从列表的末尾而不是开头开始。它始终以 0 位置开头,因此第一个值的索引值为 0 ,而不是 1
我们来看一些使用eq()方法的图示。在第一个示例中,我们将使用正索引值,在第二个示例中,我们将使用负索引值。

Example1

有五个与 class ="para" 相关的段落元素。在这里,我们使用 index 参数的正值。
eq()方法返回带有索引位置1和3。因为索引从0开始,所以它返回第二个和第四个元素。
<html>
<head>
<title> jQuery eq() method </title>
<script src="/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".para").eq(1).css({ "color": "red", "fontSize": "20px", "fontWeight": "bold" });
$(".para").eq(3).css({ "color": "blue", "fontSize": "20px", "fontWeight": "bold" });
});
</script>
</head>
<body>
<h3> This is an example of using the eq() method. </h3>
<h4> Index always starts with 0, so the position of first value is 0 instead of 1. </h4>
<p class = "para"> First Paragraph </p>
<p class = "para"> Second Paragraph </p>
<p class = "para"> Third Paragraph </p>
<p class = "para"> Fourth Paragraph </p>
<p class = "para"> Fifth Paragraph </p>
</body>
</html>
输出
执行上述代码后,输出为-
jQuery eq()method

Example2

此处,我们使用的是 index 参数。 eq()方法返回索引位置为-1和-3的元素。
在输出中,我们可以看到 eq()方法返回第五个和第三个 paragraph元素。这是因为第五段的负索引值为 -1 ,而第三段的负索引值为 -3
html>
<head>
<title> jQuery eq() method </title>
<script src="/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".para").eq(-1).css({ "color": "red", "fontSize": "20px", "fontWeight": "bold" });
$(".para").eq(-3).css({ "color": "blue", "fontSize": "20px", "fontWeight": "bold" });
});
</script>
</head>
<body>
<h3> This is an example of using the eq() method. </h3>
<p class = "para"> First Paragraph </p>
<p class = "para"> Second Paragraph </p>
<p class = "para"> Third Paragraph </p>
<p class = "para"> Fourth Paragraph </p>
<p class = "para"> Fifth Paragraph </p>
</body>
</html>
输出
执行上述代码后,输出为-
jQuery eq()方法
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4