Javascript,评分乘法选项

时间:2016-01-13 13:26:17

标签: javascript

我已经阅读了很多主题,但我仍然不清楚我必须写什么来使我的check()工作。

当你选择一个选项时,它会产生多个问题(1 x 1 1 x 2等)然后用户需要填写正确答案,当按下提交按钮时,它需要将绿色和红色的坏答案。

我尝试了很多方法,但这次我看不到它哈哈。任何人都可以告诉我或让我在我的calc()

中写出正确的方向

感谢您的帮助:)

<div id="section">
  <h2>De toets</h2>
  <p>Welke toets wil je maken?</p>
  <label for="toetsmenu"></label>
  <select id="toetsmenu" onchange="toets()">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
  </select>
  <div id="toetsding"></div>
  <script>
    function toets() {
      var x = document.getElementById("toetsmenu").value;

      document.getElementById("toetsding").innerHTML = "";
      for (i = 1; i < 11; i++) {
        document.getElementById("toetsding").innerHTML += x + " x " + i +
          " = <input type='text' id='test'>" + "<br>";
      }
      document.getElementById("toetsding").innerHTML += "<input type='submit' value='check' id='sub' onclick='calc()'>"
    }

    function calc() {

    }
  </script>
</div>

1 个答案:

答案 0 :(得分:1)

创建<input>元素时,您需要为每个元素分配一个唯一ID:id='test" + i + "

calc()函数中,您只需通过循环中的ID访问它们并检查结果

&#13;
&#13;
function toets() {
  var x = document.getElementById("toetsmenu").value;

  document.getElementById("toetsding").innerHTML = "";
  for (i = 1; i < 11; i++) {
    document.getElementById("toetsding").innerHTML += x + " x " + i +
      " = <input type='text' id='test" + i + "'>" + "<br>";
  }
  document.getElementById("toetsding").innerHTML += "<input type='submit' value='check' id='sub' onclick='calc()'>"
}

function calc() {
  var x = document.getElementById("toetsmenu").value

  for (i = 1; i < 11; i++) {
    var input = document.getElementById("test" + i)
    var result = input.value
    console.log(input.value)
    if (result == x * i) {
      input.className = "correct"
    } else {
      input.className = "wrong"
    }
  }

}

toets()
&#13;
.wrong {
  background-color: red;
}
.correct {
  background-color: green;
}
&#13;
<div id="section">
  <h2>De toets</h2>
  <p>Welke toets wil je maken?</p>
  <label for="toetsmenu"></label>
  <select id="toetsmenu" onchange="toets()">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
  </select>
  <div id="toetsding"></div>
</div>
&#13;
&#13;
&#13;