jQuery eq() 方法



jQuery 中的eq()方法用於將匹配元素集縮減到指定索引處的元素。

該方法接受一個名為“index”的引數,該引數指示元素的位置。此索引可以是正數或負數。索引值將從 0 開始,依此類推。這意味著第一個元素的索引號為 0。

如果我們提供“負”值作為索引,它將從所選元素的末尾而不是開頭開始索引計數。

語法

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

$(selector).eq(index)

引數

此方法接受以下引數:

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

示例 1

在以下示例中,我們使用 eq() 方法選擇第二個列表項,並在單擊時突出顯示它:

<html>
<head>
<script src="https://code.jquery.com/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.jquery.com/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.jquery.com/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.