javascript - JS : How would I display a decrementing value through an html header?(及更多)

标签 javascript html loops increment

基本上,我正在制作一个简单的 javascript/html 网页游戏,您可以在其中猜测一个数字,并且有 3 次猜对的机会。我在显示玩家剩余的尝试次数时遇到问题(卡在三次)。应该发生的颜色变化也没有发生。

刷新后也不会重置页面的显示(需要玩 5 次游戏才能重置)。

也许我的 for 循环/if 语句很奇怪?

这是我的代码。

var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));

function handleGuess(choice) {
guesses--; //subtract one guess
if (guesses > 0) {
if (choice != random) {
  document.body.style.backgroundColor = "#CC0000";
  var x = "";
  x = x + "You have " + guesses + " chances left" + "<br>";
  document.getElementById("demo").innerHTML = x;
} else {
  var x = "";
  x = x + "You win!" + "<br>";

  document.getElementById("demo").innerHTML = x;

  document.body.style.backgroundColor = "#009000";
  //return false; 
}
} else {
//running out of turns
var x = "";
x = x + "Game Over!" + "<br>";

document.getElementById("demo").innerHTML = x;

document.body.style.backgroundColor = "#FF0000";
//return false;

}
}

最佳答案

提示是一个阻塞事件,因此在出现提示之前您不会看到页面更新...请尝试下面的示例,其中 setTimeout用于允许延迟...

var guesses = 3;
var random = Math.floor((Math.random() * 10) + 1);
//start the guessing
handleGuess(prompt("Pick a number to win the game!"));

function handleGuess(choice) {
  guesses--; //subtract one guess
  if (guesses > 0) {
    if (choice != random) {
      document.body.style.backgroundColor = "#CC0000";
      var x = "";
      x = x + "You have " + guesses + " chances left" + "<br>";
      document.getElementById("demo").innerHTML = x;
      setTimeout(function() {
        handleGuess(prompt("Try again!"));
        },1000);//wait 1 second
    } else {
      var x = "";
      x = x + "You win!" + "<br>";

      document.getElementById("demo").innerHTML = x;

      document.body.style.backgroundColor = "#009000";
      //return false; 
    }
  } else {
    //running out of turns
    var x = "";
    x = x + "Game Over!" + "<br>";

    document.getElementById("demo").innerHTML = x;

    document.body.style.backgroundColor = "#FF0000";
    //return false;

  }
}
<h1 id="demo">You have 3 chances to guess the correct number.</h1>

<br>

关于javascript - JS : How would I display a decrementing value through an html header?(及更多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40006014/

相关文章:

Javascript 创建动态链接但忽略现有链接

JavaScript 示例代码

php - 如何在同一个表的另一个字段上填充一个字段的值

python - 避免嵌套for循环python

php - 如何生成优惠券代码,检查数据库是否唯一,如果不唯一则生成新的

javascript - Ajax 请求、数据库和安全

javascript - 上传前可以在 html 表单上调整图像(客户端)的大小吗?

html - 如何使方形图像适合矩形 div 的内部?

html - 将 Font-awesome 插入符号向上放置,插入符号向下堆叠相邻

javascript - 我什么时候需要使用 hasOwnProperty()?