Usage: 1. Used to specify the function to be run for each matching element. The syntax is "$(selector).each(function(index,element))"; 2. Used to traverse the specified object and Array, the syntax is "$.each (object or array to be traversed, function used for loop execution)".
The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.
1. The each() method specifies the function to be run for each matching element.
Tip: Returning false can be used to stop the loop early.
$(selector).each(function(index,element))
function(index,element)required. Specifies the function to run for each matching element.
The example is as follows:
<html> <head> <script type="text/javascript" src="/jquery/jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $("li").each(function(){ alert($(this).text()) }); }); }); </script> </head> <body> <button>输出每个列表项的值</button> <ul> <li>Coffee</li> <li>Milk</li> <li>Soda</li> </ul> </body> </html>
Output result:
After clicking the button:
2. The jQuery.each() function is used to traverse the specified objects and arrays.
Syntax
$.each( object, callback )
object Object type specifies the object or array that needs to be traversed.
callback Function type specifies the function used for loop execution.
Examples are as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="js/jquery.min.js"></script> </head> <body> <script> $(function () { $.each([52, 97], function(index, value) { alert(index + ': ' + value); }); }) </script> </body> </html>
Output results:
##Related video tutorial recommendations:The above is the detailed content of What is the usage of each in jquery. For more information, please follow other related articles on the PHP Chinese website!