我需要帮助使一个按钮在java脚本中生成一个随机数,我希望当按下该按钮时它会生成一个介于1-10之间的随机数,然后再次按下该按钮以生成一个新的随机数,但是每次按下按钮时显示的两个数字的总和。例如按钮按下并且计算机生成3按钮按下并且计算机生成2但显示2 + 3的总和所以5
<!DOCTYPE html>
<html>
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Merienda+One' rel='stylesheet' type='text/css'>
<title>
Blackjack
</title>
<body>
<head>
<h1>
<i>BLACKJACK</i>
</h1>
<h4>
Computers Cards:
<input type="text" id="computerscards">
<br>Player 1 cards:
<input type="text" id="playerscards">
</h4>
</head>
<input type="button" value="start" onclick="document.getElementById('playerscards').value =
random();document.getElementById('computerscards').value = 18">
<input type="button" value="deal" onclick="document.getElementById('playerscards).value = dealcard">
<input type="button" value="stand" onclick="">
<input type="button" value="next" onclick="">
<p>Press hit if you would like to draw another card
<br> press stand if you do not wish to draw another card
<br> press next if you want to start the next round</p>
</body>
<script src="java.js"></script>
</html>
JAVASCRIPT
var total =
var randomnumber = Math.floor(Math.random() * 10 + 1);
function random() {
return randomnumber;
}
function dealcard() { }
答案 0 :(得分:0)
多次设置var total =
时,您覆盖该变量。相反,您应该将其设置为0
的静态值,并将其更新为您在按钮单击时调用的函数 。您可以使用total +=
添加现有值,这是表示total = total + ...
的简写方式。
这是一个展示这个的真正精简的例子:
var total = 0;
function dealcard() {
total += Math.floor(Math.random() * 10 + 1);
document.getElementById('playerscards').value = total;
}
Player 1 cards: <input type="text" id="playerscards">
<br />
<button onclick="dealcard()">Deal</button>
希望这有帮助! :)