jQuery雜項each()方法



jQuery 中的 each() 方法用於迭代 jQuery 物件,對每個匹配的元素執行一個函式。換句話說,對於匹配集合中的每個元素,都會執行提供的函式。

語法

以下是 jQuery 雜項 each() 方法的語法:

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

引數

以下是上述語法的描述:

  • function: 對每個匹配元素執行的函式。
  • index: 匹配集合中當前元素的基於零的索引。
  • element: 正在處理的當前 DOM 元素。

示例 1

在下面的示例中,我們使用 each() 方法來更改每個段落的文字:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p").each(function(index, element) {
                $(element).text("Paragraph " + (index + 1));
            });
        });
    </script>
</head>
<body>
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <p>Third paragraph</p>
</body>
</html>	

執行後,它根據段落元素在集合中的位置,將每個 p 元素的文字更改為“段落 1”、“段落 2”和“段落 3”。

示例 2

在這個示例中,我們使用 each() 方法更改每個列表項的背景顏色:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").each(function(index, element) {
                var colors = ["lightblue", "lightgreen", "yellow"];
                $(element).css("background-color", colors[index % colors.length]);
            });
        });
    </script>
</head>
<body>
    <ul>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
        <li>List item 4</li>
    </ul>
</body>
</html>

執行後,它會根據列表項在集合中的位置,以迴圈模式將每個 li 元素的背景顏色設定為“紅色”、“綠色”或“藍色”。

jquery_ref_miscellaneous.htm
廣告
© . All rights reserved.