首页  >  文章  >  web前端  >  jQuery通用的全局遍历方法$.each()用法实例

jQuery通用的全局遍历方法$.each()用法实例

高洛峰
高洛峰原创
2016-12-29 10:48:311276浏览

本文实例讲述了jQuery通用的全局遍历方法$.each()用法。分享给大家供大家参考,具体如下:

1.test.json文件代码:

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

2.html代码:

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

3.jQuery代码:

<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>

希望本文所述对大家jQuery程序设计有所帮助。

更多jQuery通用的全局遍历方法$.each()用法实例相关文章请关注PHP中文网!


声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn