Home >Web Front-end >JS Tutorial >How to use each method within jQuery in a project

How to use each method within jQuery in a project

php中世界最好的语言
php中世界最好的语言Original
2018-06-15 15:40:341555browse

This time I will show you how to use the each method in jQuery in the project, and what are the precautions for using the each method in jQuery in the project. The following is a practical case, let's take a look.

Overview:

The each() method specifies a function to run for each matching element.

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='button']").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>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Angular CLI Angular 5 practical project demonstration

React rendering transformation on the server

The above is the detailed content of How to use each method within jQuery in a project. 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