jQuery each() 方法



jQuery 中的each()方法迭代一個 jQuery 物件,對集合中每個匹配的元素執行指定的函式。

此方法接受一個必需引數:一個“回撥函式”,它將對匹配集合中的每個元素執行。回撥函式接受兩個附加引數:“index”“element”。“index”引數表示集合中當前元素的索引位置,“element”引數表示正在迭代的當前元素。

語法

以下是 jQuery 中 each() 元素的語法:

$(selector).each(function(index,element))

引數

此方法接受以下引數:

  • function(index, element): 對集合中每個元素執行的函式。

示例 1

在下面的示例中,我們使用 each() 方法迭代每個<li> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('li').each(function(index, element) {
        alert('Index: ' + index + ', Element: ' + $(element).text());
    });
});
</script>
</head>
<body>
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
</body>
</html>

當我們執行上述程式時,對於每個li 元素,都會顯示一個警報,顯示其索引。

示例 2

在這個例子中,each() 方法將迭代每個 <input> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $('input[type="text"]').each(function(index, element) {
        alert('Index: ' + index + ', Value: ' + $(element).val());
    });
});
</script>
</head>
<body>
<input type="text" value="Input 1"><br>
<input type="text" value="Input 2"><br>
<input type="text" value="Input 3">
</body>
</html>

對於找到的每個輸入元素,都會顯示一個警報,顯示其在匹配元素集合中的索引及其值。

jquery_ref_traversing.htm
廣告
© . All rights reserved.