我浏览了网络/文档,但无法找出为什么这不起作用。
我正在尝试从 JSON 文件中插入数据(引号):{
"quotesArray":[{
"personName": "Albert Einstein",
"quote": "Look deep into nature, and then you will understand everything better."
},
{
"personName": "Stephen Hawking",
"quote": "Look deep into nature, and then you will understand everything better."
},
{
"personName": "Confucius",
"quote": "Life is really simple, but we insist on making it complicated."
}]}
使用以下 JS 进入一个简单的 HTML div:
$(document).ready(function() {
$("#realquote").on("click", function() {
$.getJSON('/json/quotes.json', function(data) {
var html = " ";
data.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'text-output'>";
keys.forEach(function(key){
html += val[key];
});
html += "</div>"
});
$(".realquote").html(html);
});
});
});
但每次,我都会收到错误:TypeError: data.forEach is not a function”,我不知道为什么。
如果有人能将我推向正确的方向,将不胜感激!
原文由 Steven 发布,翻译遵循 CC BY-SA 4.0 许可协议
data
是一个没有.forEach
方法的常规对象。您应该遍历对象的quotesArray
属性。