[英]Get all the items from JSON with getJSON
I try to get the question from a JSON file with getJSON function. 我尝试使用getJSON函数从JSON文件中获取问题。 I don't know why, but I get on the screen only first question from the JSON file.
我不知道为什么,但是我只从屏幕上看到了JSON文件中的第一个问题。 Where am I wrong?
我哪里错了?
JS: JS:
$.getJSON('data.json', function(data) {
console.log(data);
$.each(data, function(index, obj) {
var insertField = '<ul>';
insertField += '<li>' + obj.question + '</li>';
insertField += '</li>';
$("#json-data").html(insertField);
});
});
HTML: HTML:
<div id="json-data"></div>
JSON: JSON:
[
{
"question" : "Va este permisa trecerea peste marcajul longitudinal din imagine?",
"image" : "images/categoria-b/1.jpg",
"answers" : [
{"id" : 0, "text" : "A. Da, deoarece linia discontinua este cea mai apropiata de vehiculul pe care il conduceti;" },
{"id" : 1, "text" : "B. Nu, deoarece este un marcaj dublu;" },
{"id" : 2, "text" : "C. Nu, deoarece in acest caz depasirea este interzisa." }
],
"correct" : 0
},
{
"question" : "Care vehicule nu au prioritate de trecere?",
"answers" : [
{"id" : 0, "text" : "A. Vehiculele care executa virajul spre dreapta, fata de cele care circula in sens opus;" },
{"id" : 1, "text" : "B. Vehiculele care coboare fata de cele care urca, daca in sensul de mers al celor care urca se afla un obstacol imobil;" },
{"id" : 2, "text" : "C. Vehiculele care se pun in miscare la culoarea verde a semaforului." }
],
"correct" : 1
}
]
You're overwriting the contents of <div id="json-data"></div>
with each iteration by using $("#json-data").html(insertField);
您每次使用
$("#json-data").html(insertField);
覆盖<div id="json-data"></div>
$("#json-data").html(insertField);
. 。 You can either use
$("#json-data").append(insertField);
您可以使用
$("#json-data").append(insertField);
or for better performance create a string and then use $.html()
once after the loop completes: 为了获得更好的性能,请创建一个字符串,然后在循环完成后使用
$.html()
一次:
$.getJSON('data.json', function(data) {
console.log(data);
var htmlString = '';
$.each(data, function(index, obj) {
htmlString += '<ul>';
htmlString += '<li>' + obj.question + '</li>';
htmlString += '</ul>';
});
$("#json-data").html(htmlString);
});
This method results in only one DOM manipulation :) 此方法仅导致一种DOM操作:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.