首页 > 解决方案 > 如何按随机整数/变量(onclick)进行计数?

问题描述

我正在尝试模拟红点和蓝点之间的比赛。如果一个点等于或超过输入到文本框中的距离值,则该点获胜。截至目前,当您单击“采取一步!”时 按钮,每个点的位置/距离增加 1。我不知道该怎么做是让位置/距离增加一个随机整数,在这种情况下,一个从 1 到 3 的随机整数。我怎么能去做?

这是我所拥有的:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Dot Race</title>
    <link href="dotrace.css" type="text/css" rel="stylesheet" />
    <script type="text/javascript">
      function TakeAStep() {
        var x, y, redcount, bluecount, distance;

        x = Math.floor(Math.random() * 3) + 1;
        y = Math.floor(Math.random() * 3) + 1;
        redcount = document.getElementById("reddotspan").innerHTML++;
        bluecount = document.getElementById("bluedotspan").innerHTML++;
        distance = parseFloat(document.getElementById("DistanceBox").value);

        if (redcount >= distance && bluecount >= distance) {
          alert("They tied!");
        } else if (redcount >= distance) {
          alert("Red wins!");
        } else if (bluecount >= distance) {
          alert("Blue wins!");
        }
      }
    </script>
  </head>
  <body>
    <h2>Dot Race</h2>
    <p>
      Race distance: <input type="text" id="DistanceBox" placeholder="0" />
      <br>
      <span class="red">Red dot location:</span> <span id="reddotspan">0</span>
      <br>
      <span class="blue">Blue dot location:</span>
      <span id="bluedotspan">0</span>
      <hr>
      <input type="button" value="Take a step!" onclick="TakeAStep();" />
    </p>
    <div id="OutputDiv"></div>
  </body>
</html>

标签: javascripthtml

解决方案


您正在增加 and 的值,redcount但这与andbluecount无关。xy

x=我在和之后添加了这些行y=。似乎解决了根本原因。

document.getElementById("reddotspan").innerHTML=parseInt(document.getElementById("reddotspan").innerHTML)+x;
redcount = document.getElementById("reddotspan").innerHTML;
document.getElementById("bluedotspan").innerHTML=parseInt(document.getElementById("bluedotspan").innerHTML)+y;
bluecount = document.getElementById("bluedotspan").innerHTML;
distance = parseFloat(document.getElementById("DistanceBox").value);

推荐阅读