点击该按钮将触发
each()方法。我们将此方法应用于
li 元素。因此,此方法将遍历每个
li 元素。该函数针对每个选定的
li 执行,并使用警报框显示相应的
li 元素的文本。
此处,我们未使用该参数回调函数的值。
<!DOCTYPE html> <html> <head> <title> jQuery each() method </title> <script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <h2> Welcome to the lidihuo.com </h2> <ul> <li> First element </li> <li> Second element </li> <li> Third element </li> <li> Fourth element </li> </ul> <p> Click the following button to see the list of <b> li </b> elements. </p> <button onclick = fun()> Click me </button> <script> function fun(){ $(document).ready(function(){ $("li").each(function(){ alert($(this).text()) }); }); } </script> </body> </html>
输出
Welcome to the lidihuo.com
First element
Second element
Third element
Fourth element
Click the following button to see the list of li elements.
类似地,由于四个
li 元素,将显示四个警报框。
Example2
在此示例中,我们使用的回调函数的参数值为
index 和
element 。
我们将
each()方法应用于
li元素。因此,该方法将从索引
0 开始对li元素进行迭代。它将在每个选定的
li 元素上执行并更改相应元素的背景颜色。
一旦函数返回
false ,迭代就会停止。此处有六个
li 元素,当功能到达
id ="i4" 的元素时,该函数将停止。尽管它是第四个元素,但是索引从
0 开始,因此该元素的位置为
3 。
<!DOCTYPE html> <html> <head> <title> jQuery each() method </title> <script src="/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> body{ text-align: center; } ul{ list-style-type: none; float: left; } li { width: 40px; height: 40px; margin: 5px; padding: 5px; font-size: 20px; float: left; border: 2px solid blue; } button{ font-size: 20px; } </style> </head> <body> <h2> Welcome to the lidihuo.com </h2> <ul> <li> 1 </li> <li> 2 </li> <li> 3 </li> <li id = "i4"> Stop </li> <li> 5 </li> <li> 6 </li> </ul> <button onclick = "fun()"> Click me </button> <p></p> <script> function fun() { $(document).ready(function(){ $("li").each(function(index, element) { $(element).css("background", "lightgreen"); if ($(this).is("#i4")) { $("p").text("Index begins with 0. So, the function stopped at position: " + index ).css("fontSize", "20px"); return false; } }); }); } </script> </body> </html>