本文實(shí)例講述了jQuery通用的全局遍歷方法$.each()用法。分享給大家供大家參考,具體如下:
1.test.json文件代碼:
[ { "username": "張三", "content": "沙發(fā)." }, { "username": "李四", "content": "板凳." }, { "username": "王五", "content": "地板." } ]
2.html代碼:
<p> <input type="button" id="send" value="加載"/> </p> <div class="comment">已有評(píng)論:</div> <div id="resText" ></div>
3.jQuery代碼:
<script src="http://www.gimoo.net/t/1901/jquery-1.3.1.js" type="text/javascript"></script> <script type="text/javascript"> /* 1.$.each()是jquery的一個(gè)通用的遍歷方法,可用于遍歷對(duì)象和數(shù)組 2.$.each()函數(shù)不同于jquery對(duì)象的each()方法,它是一個(gè)全局函數(shù),不操作jquery對(duì)象,而是以一個(gè)數(shù)組或者對(duì)象作為第一個(gè)參數(shù),以一個(gè)回調(diào)函數(shù)作為第二個(gè)參數(shù)。回調(diào)函數(shù)擁有兩個(gè)參數(shù):第一個(gè)參數(shù)為對(duì)象的成員或數(shù)組的索引,第二個(gè)參數(shù)為對(duì)應(yīng)變量或內(nèi)容 */ $(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>
更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery擴(kuò)展技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery拖拽特效與技巧總結(jié)》、《jQuery表格(table)操作技巧匯總》、《jquery中Ajax用法總結(jié)》、《jQuery常見經(jīng)典特效匯總》、《jQuery動(dòng)畫與特效用法總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。