[英]How do I use inner.HTML in a function?
我试图创建一个HTML / Js货币计数器,但是如果我进行更新,它将更新一个刻度,然后将其重置为旧值。 我尝试创建一个名为update的函数,并使其在每次货币值更改时都运行,但这也不起作用。
<html>
<head>
<title>Betting Simulator Test!</title>
</head>
<body>
<br/>
<p id="p1">You have 500$</p>
<br/>
<form name="CoinFlip" action="" onsubmit="Create()" method="post">
Coins: <input type="text" name="Csubmit">
<input type="submit" value="Flip the Coin">
</form>
<script type="text/javascript">
Balance = 500;
function Game() {
if(Balance >= 1) {
var Coin = confirm("You have put " + sub + "$ in the CoinFlip!");
if(Coin == true) {
var flip = true
if(flip == true) {
alert("You won " + sub + "$");
Balance = Balance + sub*2 - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
} else {
alert("You lost " + sub + "$");
Balance = Balance - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
}
} else {
}
} else {
alert("You ran out of Money");
}
}
function Create() {
sub = document.forms["CoinFlip"]["Csubmit"].value;
if(sub <= Balance && sub > 0) {
Game();
} else {
alert("value does not make any sense!");
}
}
</script>
</body>
您有多个问题。 第一个是每次播放时都提交一个表单,因此页面会刷新,并且所有内容都会丢失。 您可以找到一种避免这种情况的解决方法( 请参阅此 ),但是在这种情况下,实际上不需要表单。
同样,用户总是会赢,因为您总是将flip
设置为true
。 您可以使用以下代码段模拟随机获胜:
var win = Math.round( Math.random() ); // 1 or 0 (truthy or falsy)
这是一个工作示例:
var balance = 500; document.getElementById('flip').addEventListener('click', play); function play(){ // parseInt() converts a String to an integer (10 is for decimal base) var bet = parseInt(document.getElementById('bet').value, 10); if(bet <= balance && bet > 0) { var accepted = confirm("Do you really want to bet " + bet + "$?"); if(accepted) { var win = Math.round( Math.random() ); // Random win if(win) { alert("You won " + bet + "$!"); balance += bet; } else { alert("You lost " + bet + "$..."); balance -= bet; } if(!balance){ alert('You ran out of money...'); } document.getElementById('p1').textContent = "You have " + balance + "$"; } document.getElementById('bet').value = 0; } else { alert("Your bet makes no sense!"); } }
<p id="p1">You have 500$</p> <p>Coins: <input type="number" value="0" id="bet"> <button id="flip">Flip the coin</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.