Home >Web Front-end >JS Tutorial >Detailed explanation of the use of each method in jQuery

Detailed explanation of the use of each method in jQuery

亚连
亚连Original
2018-05-29 15:38:091506browse

each() method specifies a function to run for each matching element. This article mainly introduces you to the detailed explanation of the use of each method in jQuery. Friends who need it can refer to it

Overview:

The each() method is specified for each match The element specifies the function to run.

Returning false can be used to stop the loop early, equivalent to break.

Returning true can end this loop, which is equivalent to continue.

Syntax:

$(selector).each(function(index,element){ })
    index - 选择器的 index 位置
    element - 当前的元素(也可使用 "this" 选择器)
  $(selector).each(function(){ })
  $.each(array,function(Key,Value){ })

1. Traverse the js array

$(function(){
 var array=["aaa","bbb","ccc"];
 $.each(array,function(i,j){
  alert(i+":"+j);  //i表示索引,j代表值
 });
})

2. Traverse the Object object

var obj = new Object();
obj.name="zs";
$.each(obj, function(name, value) {
  alert(this);  //this指向当前属性的值,等价于value
  alert(name);  //name表示Object当前属性的名称
  alert(value);  //value表示Object当前属性的值
});

3. Traverse JSON objects

var json ={"name":"zhangSan","role":"student"};
$.each(json,function(key,value){
 alert(key+":"+value);
});

4. Traverse an array composed of multiple JSON objects

var json =[{"name":"Amy","role":"student"},{"name":"Tom","role":"student"}];
$.each(json, function(index, value) {
  alert("index="+index+"\n" +"name:"+value.name+"\n"+"role:"+value.role+"\n");
});

5. Traverse jQuery objects 

<head>
    <meta charset="utf-8" />
  <title>遍历jQuery对象</title>
  <script src="js/jquery-1.12.4.js"></script>
  <script type="text/javascript">
   $(function(){
    $("input[type=&#39;button&#39;]").bind("click",function(){
     $("li").each(function(){
      alert($(this).text())
      });
    });
   });
  </script>
 </head>
 <body>
  <input type="button" value="触发事件"/>
  <ul>
   <li>first</li>
   <li>second</li>
  </ul>
 </body>

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Examples of how to return to the homepage of the WeChat applet sharing page

The use and non-use of el expressions in js Empty judgment method

JS realizes the function of moving the left list to the right list

The above is the detailed content of Detailed explanation of the use of each method 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