2016-07-29 9 views
0

Итак, я пытаюсь создать приложение для викторины, следуя коду от this blog post (codepen example).Javascript не работает над приложением

Я сделал все, но JS, похоже, не работает, так как никаких вопросов или ответов или чего-либо не видно, кроме HTML и CSS. Here's my JSFiddle attempt вместе с кодом

window.onload = function() { 

    var questionArea = document.getElementsByClassName('questions')[0], 
     answerArea = document.getElementsByClassName('answers')[0], 
     checker  = document.getElementsByClassName('checker')[0], 
     current  = 0, 


     allQuestions = { 
      //question and answer list, the number is the index of the answers 
      'madrugada' : ['journey', 'dawn', 'mother', 1], 
      'manzana' : ['apple', 'insane', 'men', 0], 
      'vivir' : ['villain', 'to live', 'to go', 1], 
      'amarillo' : ['love', 'river', 'yellow', 2], 
      'almendra' : ['almond', 'cheese', 'rails', 0], 
      'cascabel' : ['jingle bell', 'helmet', 'beauty', 0], 
      'aceituna' : ['tuna', 'oil', 'olive', 2], 
      'azar' : ['king', 'chance', 'zebra', 1], 
      'milagro' : ['voyage', 'tea', 'miracle', 2], 
      'añoranza' : ['snore', 'dusk', 'longing', 2], 
      'abecedario' : ['cedar', 'alphabet', 'ability', 1], 
      'frenesí' : ['frenzy', 'freaky', 'neat', 0], 
      'hechizo' : ['spell', 'done', 'zone', 0], 
      'alma' : ['almond', 'soul', 'leaf', 1], 
      'mariposa' : ['marriage', 'pose', 'butterfly', 2], 
      'siempre' : ['person', 'always', 'simple', 1], 
      'anochecer' : ['dusk', 'anual', 'dawn', 0], 
      'chiste' : ['clean', 'cheese', 'joke', 2], 
      'ojo' : ['eye', 'eight', 'dot', 0], 
      'ojalá' : ['eyeball', 'hopefully', 'lullaby', 1] 
     }; 


    function loadQuestion(curr) { 
     //Loads questions into question area 

     var question = Object.keys(allQuestions)[cur]; 
     //remove everything in q area and add current question in 
     questionArea.innerHTML = ''; 
     questionArea.innerHTML = question; 
    } 

    function loadAnswers(curr) { 
     //Loads all the possible answers of the given question 

     var answers = allQuestions[Object.keys(allQuestions)[curr]]; 
     //empty answer area 
     answerArea.innerHTML = ''; 
     //add possible answers to answerArea 
     for (var i = 0; i < answers.length - 1; i++) { 
      var createDiv = document.createElement('div'), 
       text = document.createTextNode(answers[i]); 

      createDiv.appendChild(text); 
      //adds an onclick function to the answer; a click will execute a function to check if the answer was correct 
      createDiv.addEventListener("click", checkAnswer(i, answers)); 

      answerArea.appendChild(createDiv); 
     } 
    } 

    function checkAnswer(i, arr) { 
     //checks if answer given is same as the correct one, and if it is the last question. If it is the last question, it empties answerArea 

     return function() { 
      var givenAnswer = i, 
       correctAnswer = arr[arr.length - 1]; 

      if (givenAnswer === correctAnswer) { 
       addChecker(true); 
      } else { 
       addChecker(false); 
      } 

      if (current < Object.keys(allQuestions).length - 1) { 
       current++; 

       loadQuestion(current); 
       loadAnswers(current); 
      } else { 
       questionArea.innerHTML = '¡Fin!'; 
       answerArea.innerHTML = ''; 
      } 
     }; 
    } 

    function addChecker(bool) { 
     //adds div element to page, used to see whether answer was correct or false 

     var createDiv = document.createElement('div'), 
      txt  = document.createTextNode(current + 1); 

     createDiv.appendChild(txt); 

     if (bool) { 
      createDiv.className += 'correct'; 
      checker.appendChild(createDiv); 
     } else { 
      createDiv.className += 'false'; 
      checker.appendChild(createDiv); 
     } 
    } 
}; 

Спасибо за любую помощь!

+2

Этот код определяет кучу переменных и функций. Кроме того, он ничего не делает. Чего ты ожидал? – melpomene

ответ

1

Вы не вызывали функции, необходимые для запуска и запуска, а вы только определили их в своем коде. Просто назвать их как таковые ...

// Start the quiz right away 
loadQuestion(current); 
loadAnswers(current); 

Кроме того, не заморачиваться с window.onload для JSFiddle.


JSFiddle Link - обновленный пример

+0

ах, спасибо, простое решение :) –

+0

np! пожалуйста, не забудьте принять, если вы нашли полезным, чтобы мы могли получить немного репутации :) – scniro

+0

уверен, что я просто жду, чтобы он позволил мне принять ответ! –

Смежные вопросы