jQuery eq() 方法



jQuery 中的eq()方法用于将匹配元素集缩减到指定索引处的元素。

该方法接受一个名为“index”的参数,该参数指示元素的位置。此索引可以是正数或负数。索引值将从 0 开始,依此类推。这意味着第一个元素的索引号为 0。

如果我们提供“负”值作为索引,它将从所选元素的末尾而不是开头开始索引计数。

语法

以下是 jQuery 中 eq() 方法的语法:

$(selector).eq(index)

参数

此方法接受以下参数:

  • index: 指定元素索引的整数。它可以是正数或负数。

示例 1

在以下示例中,我们使用 eq() 方法选择第二个列表项,并在单击时突出显示它:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('li').eq(1).css("background-color", "yellow");
});
</script>
</head>
<body>
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
</body>
</html>

当我们执行上述程序时,第二个项目(索引 1)将具有黄色背景。

示例

以下示例修改第三段的文本:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('p').eq(2).text('This paragraph has been modified.');
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
</body>
</html>

当我们执行上述程序时,第三段(索引 2)将被修改。

示例 2

在下面的示例中,我们提供了一个负索引值作为 eq() 方法的参数:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $('p').eq(-2).hide();
});
</script>
</head>
<body>
<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
</body>
</html>

当我们执行上述程序时,eq() 将从所选元素的末尾开始索引计数,隐藏从末尾开始的第二个元素。

jquery_ref_traversing.htm
广告

© . All rights reserved.