Home  >  Article  >  Web Front-end  >  What is the usage of each in jquery

What is the usage of each in jquery

WBOY
WBOYOriginal
2022-04-02 18:09:522387browse

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)".

What is the usage of each in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

What is the usage of each in jquery

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:

What is the usage of each in jquery

After clicking the button:

What is the usage of each in jquery

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 + &#39;: &#39; + value);
});
})
</script>
 
</body>
</html>

Output results:

What is the usage of each in jquery

What is the usage of each in jquery

##Related video tutorial recommendations:

jQuery video tutorial

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn