2014-05-25 3 views
-1

텍스트 (질문, 답변 등)가 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) 
+1

클릭 할 때마다 currentQuestion을 0으로 재설정합니다. 'var' 선언을 이벤트 핸들러 외부에 두십시오. –

답변

2

item 객체에는 question 특성이 없습니다.

item.question[currentQuestion]에서 item[currentQuestion].question으로 변경하십시오.

관련 문제