[英]How can I iterate through an array with a 'click' event in JavaScript?
我正在做一個測驗,將使用javaScript加載文本(問題,答案等)。
到目前為止,我已經創建了兩個按鈕,(一個向前,另一個向后); 我希望按鈕在單擊時能加載我的問題...
這是數組:
var allQuestions = [{
"question": "Who was Luke's wingman in the battle at Hoth?",
"choices": ["Dak", "Biggs", "Wedge", "fx-7"],
"correctAnswer": 0
}, {//question #2 }, {//question #3 etc},...];
這是我的Js:
var button = document.querySelector('.navForward');
button.addEventListener('click', function() {
var questionOutput = " ";
var currentQuestion = 0;
var item = allQuestions;
if(currentQuestion < item.length){
currentQuestion++;
}
questionOutput += "<h4>" + item.question[currentQuestion] + "</h4> <br/>";
var update = document.getElementById("question");
update.innerHTML = questionOutput;
}, false);
有人可以解釋這個錯誤嗎?
Uncaught TypeError: Cannot read property '1' of undefined script.js:84 (anonymous function)
item
對象中沒有question
屬性,因為它是一個數組。
將item.question[currentQuestion]
更改為item[currentQuestion].question
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.