我想用jQuery做一个测验,并从外部Json文件中提取问题和答案。jQuery .each()只打印来自外部Json的最后一项
我的问题是,我的foreach循环只打印出Json项目中的最后一个元素。
这是我的Jquery:
function postData(data) {
var html = "";
$.each(data, function(key, value) {
html += "<ul><h3><span>" + key + "</span></h3>";
$.each(value.answers, function(i, j){
html += "<li>" + j.answer + "</li>";
});
html += "</ul>";
});
$('#content').append(html);
};
而在我的JSON文件的数据的一个例子是:
{
"Question Title":
{
"answers":
[{
"answer" : "answer one",
"answer" : "answer two",
"answer" : "answer three",
"answer" : "answer four"
}]
},
"Question title two":
{
"answers":
[{
"answer" : "True",
"answer" : "False"
}]
}
}
但是唯一的答案,我得到的是:
Question title
- answer 4
Question title two
- False
我只是想通过它们奇怪地循环,还是我没有正确地打印对象?
让我知道你是否需要我澄清任何事情。谢谢。
HTML是无效的,'h3'不能成为孩子'ul' – charlietfl 2015-02-06 06:34:39