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
广告