好吧,所以我在Codeacademy上制作了一个简单的JavaScript硬币翻转游戏,只是为了个人练习,我试图将它输出到HTML。它“工作”很好但我想要它做的是使它输出与我最初制作游戏时输出到控制台日志的方式相同。所以说我“玩”游戏三次,输出应该看起来像......
It took 3 flips to get tails!
Didn't get it on flip 1
Didn't get it on flip 2
It took 1 flip to get tails!
It took 5 flips to get tails!
Didn't get it on flip 1
Didn't get it on flip 2
Didn't get it on flip 3
Didn't get it on flip 4
然而,输出只显示游戏的“最后”行,所以就像上面的例子中一样,HTML上输出的唯一内容就是“没有在翻转4上获得它”。这是小提琴:http://jsfiddle.net/o24nzpvw/
这是我的代码:
<!DOCTYPE html>
<html>
<body>
<script>
function coinFlip(){
input = false;
do {
var coinFace = Math.floor(Math.random() * 2);
flipTimes = 1;
while(coinFace === 0){
flipTimes += 1;
var coinFace = Math.floor(Math.random() * 2);
}
if(flipTimes == 1){
document.getElementById("output").innerHTML = "It took " + flipTimes + " flip to get tails! <br>";
} else {
document.getElementById("output").innerHTML = "It took " + flipTimes + " flips to get tails! <br>";
}
for (i = 1; i < flipTimes; i++){
document.getElementById("output").innerHTML = "Didn't get it on flip " + i + " <br>";
}
var input = false;
var input = confirm("Confirm to play again - Cancel to exit");
}
while (input !== false);
}
</script>
<button onclick="coinFlip()">Flip Coin!</button>
<p id="output"></p>
</body>
那么如何解决这个问题并“打印”当用户玩每个游戏时发生的一切,就像最初在控制台日志中所做的那样。我正在考虑尝试添加和返回数组,但我不确定这是否是最优雅(甚至可信)的解决方案。感谢大家!
答案 0 :(得分:1)
而不是陈述
document.getElementById("output").innerHTML =
使用
document.getElementById("output").innerHTML +=
答案 1 :(得分:1)
只需将输出行更改为+ =即可追加而不删除上一个文本:
document.getElementById("output").innerHTML = "Didn't get it on flip " + i + " <br>";
到
document.getElementById("output").innerHTML += "Didn't get it on flip " + i + " <br>";
以下是工作版本: