简体   繁体   English

如何将数据从JavaScript文件动态附加到html文件

[英]How to append data from JavaScript file to the html file dynamically

I have to build JS multi select questionnaire. 我必须构建JS多选问卷。

In order to read the json details I use the following code: 为了阅读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;
    });
});

I have to shoe all of the questions&answers in the same page but every time with different content (aka question&answer). 我必须将所有问题和答案都放在同一页面中,但每次都具有不同的内容(又名问题和答案)。 I have to move between questions by back and forward buttons. 我必须通过前进和后退按钮在问题之间移动。 How do I display the values of the different question dynamically in the html? 如何在html中动态显示其他问题的值?

If you have all the questions in a list, as it appears you do, the jQuery to dynamically change the question content is pretty trivial. 如果您将列表中的所有问题都显示在列表中,那么就好像您所做的那样,动态更改问题内容的jQuery非常简单。 We can create a function, and pass parameters to the function telling it to move forwards or backwards in the array of questions, as long as it doesn't extend outside the array. 我们可以创建一个函数,并将参数传递给该函数,告诉它在问题数组中向前或向后移动,只要它不扩展到数组之外即可。 An example of this is here . 一个例子在这里

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);
});

You should be able to loop through your questions and append the JSON data to a blank array in place of testArray . 您应该能够遍历所有问题,并将JSON数据附加到空白数组以代替testArray

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM