Quizgame选择在Javascript中无法正常工作

时间:2015-07-09 08:44:15

标签: javascript html

我尝试在Javascript和HTML中创建一个小小的quizgame,但它还没有正常工作。如果我选择正确的答案并让它验证,我输出错误。在我的函数showExercise中,我尝试在调用时以不同的顺序设置可能的答案。因此,用户无法通过模式选择正确的答案。我感谢任何建议和更正。

这是我的代码:

<!DOCTYPE html>
<html>

  <head>
    <title>Quizgame</title>
  </head>

  <body>

    <h1>Quizgame</h1>
    <form>
      <fieldset>
        <legend id="question">Quizgame</legend>
        <input type="radio" name="choice" id="1" value="1">
        <label for="1">Placeholder</label><br>
        <input type="radio" name="choice" id="2" value="2">
        <label for="2">Placeholder</label><br>
        <input type="radio" name="choice" id="3" value="3">
        <label for="3">Placeholder</label><br>
        <input type="radio" name="choice" id="4" value="4">
        <label for="4">Placeholder</label><br>
        <button onclick="validateInput()">Check</button>
      </fieldset>
    </form>

    <script type="text/javascript">

      var exercise = [];
      var index = 0;

      exercise[index] = {
        question:       "Convert this binary number 01000001 to a decimal number:",
        correctAnswer:  "65",
        answer:         [ "127", "33", "42", "65" ]
      };
      index++;
      exercise[index] = {
        question:       "How many combinations can you reach with 3 bits?",
        correctAnswer:  "8",
        answer:         [ "11", "9", "6", "8" ]
      };

      function random( from, to ) 
      {
        min = from > to ? to : from;
        max = to < from ? from : to;
        return( Math.floor( Math.random() * (max - min + 1 ) + min ) );
      }

      function showExercise( val ) 
      {
        document.getElementById( "question" ).innerHTML = exercise[val].question;
        for( var i = 0; i < 4; i++ )
        {
          var index = random( 0, 3 - i );
          console.log(index);
          document.getElementsByTagName( "label" )[i].innerHTML = exercise[val].answer[index];
          exercise[val].answer[index] = exercise[val].answer[3 - i];
        }
      }

      randV = random( 0, index );

      function validateInput()
      {
        var radio = document.getElementsByName( "choice" );
        for( var i = 0; i < radio.length; i++ )
        {
          if( radio[i].checked )
          {
            if( exercise[randV].answer[i] == exercise[randV].correctAnswer[0] )
            {
              alert("Right");
            }
            else
            {
              alert( "Wrong" );
            }
            break;
          }
        }
      }

      showExercise( randV );
    </script>

  </body>

</html>

1 个答案:

答案 0 :(得分:1)

您的代码中的问题是您将随机顺序中的可能答案分配给单选按钮的标签,但是单选按钮与答案数组中代表的答案的索引映射将丢失。

要解决此问题,我对您的代码进行了最小的更改,以将映射存储在每个单选按钮的value属性中。然后,当用户进行选择并单击CHECK时,将检索所选单选按钮的映射并用于查找答案数组。

<body>
<form id="form1" runat="server">
<center>
  <div id="box">Drag & Drop files from your machine on this box.</div>
  <br />
  <input id="upload" type="button" value="Upload Selected Files" />
</center>
</form>