jQuery Universal Global Traversal Method $. each of Usage Example

  • 2021-07-01 06:25:43
  • OfStack

This article illustrates the usage of jQuery's generic global traversal method $. each (). Share it for your reference, as follows:

1. test. json file code:


[
 {
  "username": " Zhang 3",
  "content": " Sofa ."
 },
 {
  "username": " Li 4",
  "content": " Bench ."
 },
 {
  "username": " Wang 5",
  "content": " Floor ."
 }
]

2. html code:


<p>
<input type="button" id="send" value=" Loading "/>
</p>
<div class="comment"> Comments already made: </div>
<div id="resText" ></div>

3. jQuery code:


<script src="jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
/*
1.$.each() Yes jquery Adj. 1 General traversal methods can be used to traverse objects and arrays 
2.$.each() Function is different from jquery Object's each() Method, which is the 1 Global functions that do not operate jquery Object, but with the 1 Array or object as the first 1 Parameters to 1 Callback function as the first 2 Parameters. The callback function takes two arguments 1 The parameter is the index of the member or array of the object, the 2 Parameters are corresponding variables or contents 
*/
$(function(){
    $('#send').click(function() {
       $.getJSON('test.json', function(data) {
         $('#resText').empty();
         var html = '';
         $.each( data , function(commentIndex, comment) {
           html += '<div class="comment"><h6>' + comment['username'] + ':</h6><p class="para">' + comment['content'] + '</p></div>';
         })
         $('#resText').html(html);
      })
    })
})
</script>

For more readers interested in jQuery related content, please check the topics of this site: "Summary of jQuery Extension Skills", "Summary of jQuery Common Plug-ins and Usage", "Summary of jQuery Drag Effects and Skills", "Summary of jQuery Table (table) Operation Skills", "Summary of Ajax Usage in jquery", "Summary of jQuery Common Classic Special Effects", "Summary of jQuery Animation and Special Effects Usage" and "Summary of jquery Selector Usage"

I hope this article is helpful to everyone's jQuery programming.


Related articles: