迭代一个或多个对象来显示一个属性

时间:2018-03-22 23:15:34

标签: javascript html

我试图显示"问题"从我在"测验"的第一个条目开始宾语。



const quiz = {
  "0": {
    question: "Who was the lead-developer behind 'Grand Theft Auto V'?",
    answers: [
      "Rockstar Games",
      "Rockstar North",
      "2K Games",
      "Activision"
    ],
    correct: 2,
    clip: "https://giphy.com/embed/l41lXyGaSM2Gko4WA"
  },
  "1": {
    question: "'The Elder Scrolls V: Skyrim' is part of which genre?",
    answers: [
      "massively multiplayer online role-playing game (MMORPG)",
      "platformer",
      "real-time strategy game (RTS)",
      "role-Playing game (RPG)"
    ],
    correct: 4,
    clip: "https://giphy.com/embed/wG9R3HQ65ofeg"
  }
};

let currentQuestion = 0;

function renderQuestion(currentQuestion) {
  let output = document.getElementById("outputDiv");
  output.innerHTML =
    `<p> ${quiz[currentQuestion].question} </p>`;

}
&#13;
<article>
  <div id="outputDiv">
    <script>
      renderQuestion(0);
    </script>
    <!-- <button id="nextQuestion" type="button">Next</button> -->
  </div>
</article>
<script src="Scripts/script.js" />
&#13;
&#13;
&#13;

我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

The problem is where you've placed the call of renderQuestion, you need to execute that function when the DOM is totally loaded.

To avoid this, an alternative is using the event DOMContentLoaded.

const quiz = {
  "0": {
    question: "Who was the lead-developer behind 'Grand Theft Auto V'?",
    answers: [
      "Rockstar Games",
      "Rockstar North",
      "2K Games",
      "Activision"
    ],
    correct: 2,
    clip: "https://giphy.com/embed/l41lXyGaSM2Gko4WA"
  },
  "1": {
    question: "'The Elder Scrolls V: Skyrim' is part of which genre?",
    answers: [
      "massively multiplayer online role-playing game (MMORPG)",
      "platformer",
      "real-time strategy game (RTS)",
      "role-Playing game (RPG)"
    ],
    correct: 4,
    clip: "https://giphy.com/embed/wG9R3HQ65ofeg"
  }
};

let currentQuestion = 0;

function renderQuestion(currentQuestion) {
  let output = document.getElementById("outputDiv");
  output.innerHTML =
    `<p> ${quiz[currentQuestion].question} </p>`;

}
<body>
  <script>
    document.addEventListener("DOMContentLoaded", function(event) {
      console.log("DOM fully loaded and parsed");
      renderQuestion('0');
    });
  </script>
  <article>
    <div id="outputDiv">
      <!-- <button id="nextQuestion" type="button">Next</button> -->
    </div>
  </article>
</body>