Jquery – 选择随机JSON对象
我有这个jquery代码在页面加载时输出JSON文件中的条目…
$.getJSON('b.json', function(data) { $('#dictionary').empty().hide(); $.each(data, function(entryIndex, entry) { var html = ''; html += '' + entry['title'] + '
'; html += '' + entry['link_url'] + ''; html += ''; html += entry['image_src']; if (entry['quote']) { html += ''; $.each(entry['quote'], function(lineIndex, line) { html += '' + line + ''; }); if (entry['author']) { html += ' '; } html += ''; } html += ''; html += ''; $('#dictionary').append(html).fadeIn(); }); });
我需要做的是随机加载其中一个条目。
任何建议表示赞赏
非常感谢,C
JSON文件是……
[ { "title": "WESITE NAME", "link_url": "http://www.website.com", "image_src": "http://sofzh.miximages.com/jquery/recent.jpg", }, { "title": "WESITE NAME", "link_url": "http://www.website.com", "image_src": "http://sofzh.miximages.com/jquery/recent.jpg", }, { "title": "WESITE NAME", "link_url": "http://www.website.com", "image_src": "http://sofzh.miximages.com/jquery/recent.jpg", } ]
$.getJSON('b.json', function(data) { var entry = data[Math.floor(Math.random()*data.length)]; //do the same exact thing with entry }
看起来你想从数组中随机输入。
尝试:
var random_entry = entry[Math.floor(Math.random() * entry.length)]