Example of each of method usage in jQuery

  • 2020-05-09 18:12:19
  • OfStack

This article illustrates the use of the each() method in jQuery as an example. Share with you for your reference. The specific analysis is as follows:

This method can execute a function in the context of every element in the set of matched elements.

Each time a function is executed, the execution environment of the function is a different DOM element in a set of matching elements, and the index of this element in the set is passed to the function, with the index value starting at 0. This can be used to stop the loop early by returning false, which continues the function until each of the matched elements is traversed.
The each() method is different from the jQuery.each () method. The each() method can only traverse JQuery objects, while the jQuery.each () method can traverse any object.
Grammatical structure:

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

Parameter list:

参数 描述
function(index,element) 每个匹配元素定义运行的方法。
index - 可选。当前上下文元素在匹配元素集合中的索引。
element -可选。当前的元素(也可使用 "this" 选择器)。

Example code:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title>each() function - The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
  $("li").each(function(index,element){
    alert($(element).text())
  })
})
})
</script>
</head>
<body>
<ul>
  <li> The background section </li>
  <li> Zone at the front desk </li>
  <li> Database zone </li>
  <li> Adsense zone </li>
</ul>
<button id="btn"> Click to view </button>
</body>
</html>

The code above facilitates each element in the li element collection, and then returns the text in the li element.

I hope this article has helped you with your jQuery programming.


Related articles: