Jquery-选择随机JSON对象
我用这个jquery代码在页面加载时输出JSON文件中的条目Jquery-选择随机JSON对象,jquery,json,Jquery,Json,我用这个jquery代码在页面加载时输出JSON文件中的条目 $.getJSON('b.json', function(data) { $('#dictionary').empty().hide(); $.each(data, function(entryIndex, entry) { var html = '<div class="entry">'; html += '<h3 class="title">'
$.getJSON('b.json', function(data) {
$('#dictionary').empty().hide();
$.each(data, function(entryIndex, entry) {
var html = '<div class="entry">';
html += '<h3 class="title">' + entry['title'] + '</h3>';
html += '<div class="link_url">' + entry['link_url'] + '</div>';
html += '<div class="image_src">';
html += entry['image_src'];
if (entry['quote']) {
html += '<div class="quote">';
$.each(entry['quote'], function(lineIndex, line) {
html += '<div class="quote-line">' + line + '</div>';
});
if (entry['author']) {
html += '<div class="quote-author">' + entry['author'] + '</div>';
}
html += '</div>';
}
html += '</div>';
html += '</div>';
$('#dictionary').append(html).fadeIn();
});
});
看起来您需要数组中的随机项 尝试:
看起来您需要数组中的随机项 尝试:
当我向条目变量发出警报时,我得到[object object],这是因为警报无法处理数组或对象。尝试使用Firefox插件Firebug并创建一个console.log;请尝试alertentry.title;,其中title是返回的JSON对象的属性。当我警告条目变量时,我得到[object object],这是因为alert无法处理数组或对象。尝试使用Firefox插件Firebug并创建一个console.log;请尝试alertentry.title;,其中title是返回的JSON对象的属性。
[
{
"title": "WESITE NAME",
"link_url": "http://www.website.com",
"image_src": "http://www.website.com/images/recent.jpg",
},
{
"title": "WESITE NAME",
"link_url": "http://www.website.com",
"image_src": "http://www.website.com/images/recent.jpg",
},
{
"title": "WESITE NAME",
"link_url": "http://www.website.com",
"image_src": "http://www.website.com/images/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)]