Home > Web Front-end > JS Tutorial > jQuery universal global traversal method $.each() usage example

jQuery universal global traversal method $.each() usage example

高洛峰
Release: 2016-12-29 10:48:31
Original
1357 people have browsed it

The example in this article describes the usage of jQuery’s universal global traversal method $.each(). Share it with everyone for your reference, the details are as follows:

1.test.json file code:

[
 {
  "username": "张三",
  "content": "沙发."
 },
 {
  "username": "李四",
  "content": "板凳."
 },
 {
  "username": "王五",
  "content": "地板."
 }
]
Copy after login

2.html code:

<p>
<input type="button" id="send" value="加载"/>
</p>
<div class="comment">已有评论:</div>
<div id="resText" ></div>
Copy after login

3.jQuery code:

<script src="jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
/*
1.$.each()是jquery的一个通用的遍历方法,可用于遍历对象和数组
2.$.each()函数不同于jquery对象的each()方法,它是一个全局函数,不操作jquery对象,而是以一个数组或者对象作为第一个参数,以一个回调函数作为第二个参数。回调函数拥有两个参数:第一个参数为对象的成员或数组的索引,第二个参数为对应变量或内容
*/
$(function(){
    $(&#39;#send&#39;).click(function() {
       $.getJSON(&#39;test.json&#39;, function(data) {
         $(&#39;#resText&#39;).empty();
         var html = &#39;&#39;;
         $.each( data , function(commentIndex, comment) {
           html += &#39;<div class="comment"><h6>&#39; + comment[&#39;username&#39;] + &#39;:</h6><p class="para">&#39; + comment[&#39;content&#39;] + &#39;</p></div>&#39;;
         })
         $(&#39;#resText&#39;).html(html);
      })
    })
})
</script>
Copy after login

I hope this article will be helpful to everyone in jQuery programming.

For more jQuery general global traversal method $.each() usage examples related articles, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template