使用getJSON从JSON获取所有项目

时间:2016-03-08 21:18:48

标签: javascript jquery json

我尝试使用getJSON函数从JSON文件中获取问题。我不知道为什么,但我只在屏幕上看到JSON文件中的第一个问题。我哪里错了?

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:

<div id="json-data"></div>

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 
    }
]

1 个答案:

答案 0 :(得分:2)

您使用<div id="json-data"></div>在每次迭代时覆盖$("#json-data").html(insertField);的内容。您可以使用$("#json-data").append(insertField);或为了更好的性能创建字符串,然后在循环完成后使用$.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);
});

此方法仅导致一个DOM操作:)