【js与jquery】jquery的一个通用的专门用于遍历的全局方法$.each()的使用

本文介绍了一种使用jQuery从JSON文件加载数据并显示在网页上的方法。通过点击按钮触发加载功能,利用$.getJSON获取JSON数据,并用$.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="../scripts/jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
/*
1.$.each()是jquery的一个通用的遍历方法,可用于遍历对象和数组
2.$.each()函数不同于jquery对象的each()方法,它是一个全局函数,不操作jquery对象,而是以一个数组或者对象作为第一个参数,以一个回调函数作为第二个参数。回调函数拥有两个参数:第一个参数为对象的成员或数组的索引,第二个参数为对应变量或内容
*/
$(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>


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值