如何动态地将JavaScript文件中的数据附加到html文件中

How to append data from JavaScript file to the html file dynamically

本文关键字:文件 数据 html JavaScript 何动态 动态      更新时间:2023-09-26

我必须建立JS多重选择问卷。

为了读取json的详细信息,我使用以下代码:
$(document).ready(function(){
    $.getJSON("data.json", function(json) {
        var anserFor1st = json.questions[0].answers;
        var anserFor2nd = json.questions[1].answers;//If it's more than two use a loop
        document.getElementById("content").innerHTML =  JSON.stringify(anserFor1st) + "<br/>" + JSON.stringify(anserFor2nd);
        var aString = "";
        Object.keys(anserFor1st).forEach(function (k) {aString += anserFor1st[k] + "<br/>";});
        Object.keys(anserFor2nd).forEach(function (k) {aString += anserFor2nd[k] + "<br/>";});
        document.getElementById("content").innerHTML = aString;
    });
});

我必须把所有的问题和答案放在同一页,但每次都有不同的内容(又名问题和答案)。我必须通过"后退"answers"前进"按钮在问题之间切换。如何在html中动态显示不同问题的值?

如果您将所有问题都放在一个列表中,那么动态更改问题内容的jQuery非常简单。我们可以创建一个函数,并向该函数传递参数,告诉它在问题数组中向前或向后移动,只要它不扩展到数组之外。下面是一个例子:

var testArray = ["first q", "second q", "third q", "fourth q"];
var questionIndex = 0;
function updateQuestion(direction) {
    questionIndex += direction;
    if (questionIndex < testArray.length && questionIndex >= 0) {
        $(".question").html(testArray[questionIndex]);
    } else {
        questionIndex -= direction;
    }
}
$(document).ready(function () {
    updateQuestion(0);
});

您应该能够循环遍历您的问题并将JSON数据附加到空白数组中以代替testArray