我正在尝试使用 div 填充我的页面,这些 div 填充了我从 recordData.json 文件中收集的数据。
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);
});
});
我已将该函数放置在正文中的脚本标记中,但页面上没有填充任何内容。如果我遗漏了什么或者这里可能出了什么问题,有人可以告诉我吗?附:这是我的第一篇文章,所以请放轻松:)
最佳答案
我在您的 html 文件中没有看到 id 为“recordDiv”的 html 元素
$("#recordDiv").html(html);
确保 html 元素的 id 正确
另外,您似乎没有访问 json 文件“recordData”中数组的键
关于javascript - 使用 JSON 文件中的数据动态创建元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59166274/