本文實例講述了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(){ $('#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>
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery擴展技巧總結》、《jQuery常用插件及用法總結》、《jQuery拖拽特效與技巧總結》、《jQuery表格(table)操作技巧匯總》、《jquery中Ajax用法總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答