[英]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.