javascript - 如何按随机整数/变量(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>
解决方案
您正在增加 and 的值,redcount
但这与andbluecount
无关。x
y
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);
推荐阅读
- node.js - javascript node.js 读取命令行流
- python - 如何使用在 WSL(Windows Ubuntu 16)中下载的 Anaconda 分发 Python 路径作为 VSCODE 中的主要 python
- google-cloud-platform - 如何在 Google Cloud Platform 的 Compute Engine 上安装 Jenkins?
- postgresql - 多个 UPDATE ... FROM 同一行不起作用
- reactjs - 如何在链接中添加 onClick 事件
- php - 我应该把创建对象的通用逻辑放在哪里?
- ios - ios中的TextInpout自动更正显示相反[react native]
- mysql - 如何计算具有无限级别的级别?
- moqui - Moqui REST API 是否支持二进制文件作为参数?
- python - 使用 Python 收集和上传文件