每个循环的Javascript仅显示最后一个对象

时间:2018-12-03 20:17:32

标签: javascript arrays

有人可以解释为什么我的循环只显示数组的最后一个对象吗? 因为我想输出所有测验的答案 谢谢!

var allQuestions = [
    {
      question: "Welk kerstnummer draai jij grijs tijdens de feestdagen?",
      responses: [{
        text: 'Feliz Navidad',
        value: 10
      },
      {
        text: 'Baby, Its Cold Outside',
        value: 6
      },

    var currentQuestion = 0;
    var question;
    var responses;

    var questions = document.getElementById("question");
    var quizForm = document.getElementById("choiceList");

    function showQuestion() {
      question = allQuestions[currentQuestion].question;
      // choice = allQuestions[answers].responses.length;

      questions.innerHTML = "<p>" + question + "</p>";

      for (var i = 0; i < allQuestions[currentQuestion].responses.length; i++) {
        responses = allQuestions[currentQuestion].responses[i].text;
        quizForm.innerHTML = "<li>" + responses + "</li>";
      }
    }

    showQuestion();

1 个答案:

答案 0 :(得分:1)

您可以使用quizForm.innerHTML += "<li>" + responses + "</li>";,但效率不高。

我更愿意这样做:

var liEl = document.createElement("li");
liEl.innerText = "someContent";
quizForm.appendChild(liEl);

let containerElement = document.getElementById("container");
let array = ['a','b','c']


for(let i = 0; i<array.length ; i++){
  containerElement.innerHTML += '<li>'+array[i]+'</li>';
}

array = ['x','y','z']

for(let i = 0; i<array.length ; i++){
  var liEl = document.createElement("li");
  liEl.innerText = array[i];
  containerElement.appendChild(liEl);
}
<ul id="container"></ul>