我的 JSON 文件中有一个数组,我想要做的是从数组中提取单个条目并在页面加载时显示它。 我已经使用 this question and answer 到达一半了,但是我尝试调整这个答案会导致输出 html block 按顺序重复数组项,而不是简单地选择一个。
这是我得到的屏幕截图: screenshot of output
我可能做了一些非常愚蠢的事情,我希望有人能指出这一点。 我的脚本如下:
$.getJSON('recommend.json', function(data) {
var entry = data[Math.floor(Math.random()*data.length)];
$.each(data, function(entryIndex, entry) {
var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>';
html += '<span class="rec_title">' + entry['title'] + '</span><p>';
html += '<span class="rec_author">' + entry['author'] + '</span><p>';
html += '<span class="rec_blurb">' + entry['blurb'] + '</span>';
$('#recblock').append(html).fadeIn();
});
});
有任何问题请告诉我。
最佳答案
剪掉这个:
$.each(data, function(entryIndex, entry) {
$.each
的全部目的是迭代整个数组,这与您想要的相反。您之前已将 entry
定义为数据中的随机条目。
所以你将拥有:
$.getJSON('recommend.json', function(data) {
var entry = data[Math.floor(Math.random()*data.length)];
var html = '<div class="rec_img"><img src="./recs/' + entry['img'] + '" /></div>';
html += '<span class="rec_title">' + entry['title'] + '</span><p>';
html += '<span class="rec_author">' + entry['author'] + '</span><p>';
html += '<span class="rec_blurb">' + entry['blurb'] + '</span>';
$('#recblock').append(html).fadeIn();
});
关于javascript - 从 json 中提取单个项目并以 html 形式显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38577434/