从JavaScript生成的测验直到刷新才加载

时间:2014-09-26 03:34:50

标签: javascript ruby-on-rails

奇怪的问题。使用Javascript制作了一个琐事游戏,它加载---但只是在刷新之后。虽然我在(准备好)调用Javascript,但它最初只加载一个没有文本的单选按钮。但是通过刷新,一切都是固定的。知道我应该怎么做才能在页面打开时正确加载它?

在我的HTML文件中,我正在加载一个五个问题的测验:

<!-- First Trivia Example --> 

<div id="content">
       <h3 id="question"></h3>
       <div id="choices"></div>
       <p><button id="submit"></button></p>
       <p id="score"></p>
    </div>
  </div>

这些元素来自我的应用程序中的.js文件&gt;资产&gt;我的RoR文件的Javascripts目录,我准备好了。

  $(document).ready(function() { 

      var quiz = [{
      "question": "What is the full form of IP?",
      "choices": ["Internet Provider", "Internet Port", "Internet Protocol"],
      "correct": "Internet Protocol"
    }, {
      "question": "Who is the founder of Microsoft?",
      "choices": ["Bill Gates", "Steve Jobs", "Steve Wozniak"],
      "correct": "Bill Gates"
    }, {
      "question": "1 byte = ?",
      "choices": ["8 bits", "64 bits", "1024 bits"],
      "correct": "8 bits"
    }, {
      "question": "The C programming language was developed by?",
      "choices": ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"],
      "correct": "Dennis Ritchie"
    }, {
      "question": "What does CC mean in emails?",
      "choices": ["Carbon Copy", "Creative Commons", "other"],
      "correct": "Carbon Copy"
    }];


    // define elements
    var content = $("content"),
      questionContainer = $("question"),
      choicesContainer = $("choices"),
      scoreContainer = $("score"),
      submitBtn = $("submit");

    // init vars
    var currentQuestion = 0,
      score = 0,
      askingQuestion = true;

    function $(id) { // shortcut for document.getElementById
      return document.getElementById(id);
    }

    function askQuestion() {
      var choices = quiz[currentQuestion].choices,
        choicesHtml = "";

      // loop through choices, and create radio buttons
      for (var i = 0; i < choices.length; i++) {
        choicesHtml += "<input type='radio' name='quiz" + currentQuestion +
          "' id='choice" + (i + 1) +
          "' value='" + choices[i] + "'>" +
          " <label for='choice" + (i + 1) + "'>" + choices[i] + "</label><br>";
      }

      // load the question
      questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " +
        quiz[currentQuestion].question;

      // load the choices
      choicesContainer.innerHTML = choicesHtml;

      // setup for the first time
      if (currentQuestion === 0) {
        scoreContainer.textContent = "Score: 0 right answers out of " +
          quiz.length + " possible.";
        submitBtn.textContent = "Submit Answer";
      }
    }

    function checkAnswer() {
      // are we asking a question, or proceeding to next question?
      if (askingQuestion) {
        submitBtn.textContent = "Next Question";
        askingQuestion = false;

        // determine which radio button they clicked
        var userpick,
          correctIndex,
          radios = document.getElementsByName("quiz" + currentQuestion);
        for (var i = 0; i < radios.length; i++) {
          if (radios[i].checked) { // if this radio button is checked
            userpick = radios[i].value;
          }

          // get index of correct answer
          if (radios[i].value == quiz[currentQuestion].correct) {
            correctIndex = i;
          }
        }

        // setup if they got it right, or wrong
        var labelStyle = document.getElementsByTagName("label")[correctIndex].style;
        labelStyle.fontWeight = "bold";
        if (userpick == quiz[currentQuestion].correct) {
          score++;
          labelStyle.color = "green";
        } else {
          labelStyle.color = "red";
        }

        scoreContainer.textContent = "Score: " + score + " right answers out of " +
          quiz.length + " possible.";
      } else { // move to next question
        // setting up so user can ask a question
        askingQuestion = true;
        // change button text back to "Submit Answer"
        submitBtn.textContent = "Submit Answer";
        // if we're not on last question, increase question number
        if (currentQuestion < quiz.length - 1) {
          currentQuestion++;
          askQuestion();
        } else {
          showFinalResults();
        }
      }
    }

    function showFinalResults() {
      content.innerHTML = "<h2>You've completed the quiz!</h2>" +
        "<h2>Below are your results:</h2>" +
        "<h2>" + score + " out of " + quiz.length + " questions, " +
        Math.round(score / quiz.length * 100) + "%<h2>";
    }

    window.addEventListener("load", askQuestion, false);
    submitBtn.addEventListener("click", checkAnswer, false);

    });

1 个答案:

答案 0 :(得分:0)

工作正常...确认您已安装gem 'jquery-rails',同时检查application.js下的app/assets/javascript/application.js文件是否插入了Jquery ..

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .

检查app/views/layout/application.html.erb应该

<%= javascript_include_tag "application", "data-turbolinks-track" => true %>

Your Code's Demo:


当前Jquery代码中的

问题

  • 您的代码从问题2开始测验(Q2

因为您已初始化var currentQuestion  作为0// load the question  部分定义

questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " + quiz[currentQuestion].question;

(currentQuestion + 1)将成为(0 + 1),因为它从1开始索引,而数组索引从0开始这就是为什么你的第一个问题没有出现..

解决方案:var currentQuestion初始化为-1而不是0

Corrected Code's Demo