【问题标题】:Triva Game, compare radio buttons value to answer琐事游戏,比较单选按钮的值来回答
【发布时间】:2019-09-14 03:22:05
【问题描述】:

我正在使用一组对象创建一个 Trivia 游戏。我创建了一个函数,它循环显示所有问题,然后循环所有选项并将它们变成单选按钮。我一直在努力将答案与所选值进行比较,因此当计时器用完时,我可以打印出用户正确和错误的数量。有人可以指点我正确的方向吗?

function countdown() {
    var counter = 60;
    var timeCountdown = setInterval(function(){

      counter--
      $('.timer-container .time').html(counter);
      if (counter === 0) {
        clearInterval(timeCountdown);
        $('.timer-container .time').html("Times Up");
        points();
      }
    }, 1000);

    $('.timer-container').toggle();
}


let trivia = [
    {
        question: "How many wheels are on a skateboard?",
        choices: ["2",  "4", "6", "8"],
        answer: "2",
    },
    {
        question: "Who invented the kickflip?",
        choices: ["Tony Hawk", "Bam Magera", "Rodney Mullen", "Chad Muska"],
        answer: "Rodney Mullen"
    },
    {
        question: "Who did the first 900?",
        choices: ["Tony Hawk", "Tas Pappas", "Danny Way", "bob burnquist"],
        answer: "Tony Hawk",
    },
    {
        question: "What is another word for a 360 flip?",
        choices: ["Impossible Flip", "3 1/2 flip", "Tre Bomb", "Tri Flip"],
        answer: "Tre Bomb",
    }
];


function triviaQuestions() {
    for(var i = 0; i < trivia.length; i++) {   

        var questionHeader = $('<h2 class="question-' + i + '">');
        var questionHeaderContent = questionHeader.text(trivia[i].question);
        $('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + " '>");

        for (var j = 0; j < trivia.length; j++) {
            console.log(trivia[i].choices[j]);
            var questionChoices = $('<input type="radio"' + 'name="'  + i + '"'+ 'value="' + trivia[i].choices[j] + '">' + '<label>' + trivia[i].choices[j] + '</label>');
            var questionChoicesContent = questionChoices.text(trivia[i].choices[j]);
            $('.choices-container-' + i).append(questionChoices).append(questionChoicesContent);

         } 
    }  
}




$( document ).ready(function() {
    $('.start-button').on('click', function() {
        $(this).toggle();
        countdown();
        triviaQuestions();
    });

});

谢谢

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    您的points() 函数可能如下所示:

    function points() {
        var correct = 0;
        $(".choices").each(function(i){
            var questionid = $(this).attr('id').split('-')[1];
            var answer = $(this).find("input:checked").val();
            if (answer == trivia[questionid].answer) correct += 1;
        });
        $(".points-container").toggle();
        $(".points-container span").text(correct);
    }
    

    假设你的页面某处有这样的元素:

    <div class="points-container" style="display:none">Total Points: <span></span></div>
    

    假设您将 id="" 属性添加到表单元素:

    $('.question-container').append(questionHeaderContent).append("<form class='choices choices-container-" + i + "' id='choices-" + i + "'>");
    

    上面的函数循环遍历页面上的每个表单,从表单的 id 中提取 trivia 数组中的问题索引,并将给出的答案与该索引中指定的答案进行匹配。也许不是最优雅的解决方案,但它对我有用,只需对您的代码进行最少的修改。

    【讨论】:

      【解决方案2】:

      这里发生了一些事情,所以我给了你一个完整的解决方案 - 这包括计时器、问题/答案集的打印和测试功能。

      这里有一个完整的代码笔:https://codepen.io/V3Dev/pen/vYBaEVL

      详情如下 - 享受:)

      HTML

      <input id="trigger" type="button" value="Start Timer" onclick="startTimer();"/>
      <p id="timer">60 Seconds Remaining</p>
      
      
      <br>
      <input id="trigger" type="button" value="Test Answers Immediately" onclick="testAnswers();"/>
      <br><br><br>
      <div id="container"/>
      

      脚本

      //starting JSON
      let trivia = [*JSON*];
      
      //iterate over your JSON
      for (let i = 0; i < trivia.length; i++) {
      
          //print the question
          document.getElementById("container").appendChild(document.createTextNode(trivia[i].question));        
          document.getElementById("container").appendChild(document.createElement("br"));
      
          //iterate over the choices and create answer objects
          for (let i2 = 0; i2 < trivia[i].choices.length; i2++) {
      
              //print the choices
              var input = document.createElement("input");
              input.type = "radio";
              input.value = trivia[i].choices[i2];
              input.name = trivia[i].question;
              document.getElementById("container").appendChild(input);
              document.getElementById("container").appendChild(document.createTextNode(trivia[i].choices[i2]));
              document.getElementById("container").appendChild(document.createElement("br"));
      
          };
      
          //seperate questions
          document.getElementById("container").appendChild(document.createElement("br"));
          document.getElementById("container").appendChild(document.createElement("br"));
      
      
      };
      
      //test the submitted answer against the stored value
      function testAnswers(){
          let score = 0;
      
          for (let i = 0; i < trivia.length; i++) {
              let questionSelectedAnswer = getRadioValue(trivia[i].question);
              if (questionSelectedAnswer == trivia[i].answer){
                  score++;
              }
          }
          alert("You scored " + score + "/" + trivia.length);
      }
      
      //get the selected value for a collection of answers
      function getRadioValue(theRadioGroup)
      {
          var elements = document.getElementsByName(theRadioGroup);
          for (var i = 0, l = elements.length; i < l; i++)
          {
              if (elements[i].checked)
              {
                  return elements[i].value;
              }
          }
      }
      
      //set the timer logic
      var timer;
      
      function startTimer() {
          //clear any running timers
          clearInterval(timer);
      
          var secondsRemaining = 60;
      
          timer = setInterval(function() {
          secondsRemaining--;
      
          // If the count down is over run the test
          if (secondsRemaining < 1) {
              clearInterval(timer);
              testAnswers();
              secondsRemaining = 0;
          }
      
          //print the time
          document.getElementById("timer").innerHTML = secondsRemaining + " seconds remaining";
      
          }, 1000);
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-04
        • 2019-07-05
        • 1970-01-01
        相关资源
        最近更新 更多