Home  >  Article  >  Web Front-end  >  Use case of each method in jQuery

Use case of each method in jQuery

php中世界最好的语言
php中世界最好的语言Original
2018-05-10 11:58:561365browse

This time I will bring you a use case of each method in jQuery. What are the precautions when using each method in jQuery. 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:

Detailed explanation of the steps to replace node elements with jQuery

Detailed explanation of examples of interaction between Servlet3.0 and JS through Ajax

The above is the detailed content of Use case 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