我正在尝试使用填充有从recordData.json文件中收集的数据的div填充页面。
JSON文件中的每个记录应具有类似以下内容的元素:
<div class="card text-center bg-dark cardBorder" style="width: 18rem;">
<img class="card-img-top" src="images/1984.jpg" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">1984</h5>
<p class="card-text">Van Halen</p>
</div>
</div>
JSON文件的格式为:
"recordData": [
{
"name": "Let's Rock",
"artist": "The Black Keys",
"genre": "Rock",
"imagePath": "images/Let's Rock.jpg"
},
{
"name": "Brothers",
"artist": "The Black Keys",
"genre": "Rock",
"imagePath": "images/Brothers.jpg"
}, //and so on
我有这个jQuery函数:
$(function() {
$.getJSON("recordData.json", function(data) {
var html = '';
$.each(data, function(key, value) {
html += '<div class="card text-center bg-dark cardBorder" style="width: 18rem;">';
html += '<img class="card-img-top" src="'+value.imagePath+'" alt="Card image cap">';
html += '<div class="card-body">';
html += '<h5 class="card-title">'+value.name+'</h5>';
html += '<p class="card-text">'+value.artist+'</p>';
html += '</div>';
html += '</div>';
});
$("#recordDiv").html(html);
});
});
我已将函数放置在正文中的script标记中,但是页面上没有任何内容。有人可以让我知道我是否遗漏了什么东西,或者这里可能出了什么问题?附言这是我的第一篇文章,所以对我容易:)
答案 0 :(得分:0)
您在$.each
块的第一行中缺少括号。记住要使用chrome /浏览器devtools控制台快速发现这种语法错误。
$(function() {
$.getJSON("recordData.json", function(data) {
var html = '';
$.each(data, function(key, value) {
html += '<div class="card text-center bg-dark cardBorder" style="width: 18rem;">';
...
答案 1 :(得分:0)
我在您的html文件中没有看到ID为“ recordDiv”的html元素
$("#recordDiv").html(html);
确保html元素的ID是正确的
另外,您似乎无法访问json文件“ recordData”中数组的键