如果我是个傻子,我很抱歉。我刚刚开始学习 Javascript,正在搞循环。 我目前正在处理这段代码:
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">---</button>
<p id="hpcount"></p>
<p id="demo2"></p>
<script>
var health = 30;
document.getElementById("hpcount").innerHTML = health;
while (health < 0){
health = 0;
document.getElementById("demo2").innerHTML = "Game over";
break;
}
function myFunction() {
if (health>0){
health -= Math.floor(Math.random() * 10)+1;
document.getElementById("hpcount").innerHTML = health;
}
}
</script>
</body>
</html>
这个想法是,只要生命值大于 0,按钮就会从变量“生命值”中减去一个随机整数 1-10。然后,如果它低于该值,则显示“游戏结束”消息并将生命值重置为0。 然而,虽然一旦 health>0 按钮就停止工作,但该消息就不会出现,而且无论我查看语法和结构多少次,我都无法弄清楚为什么...... 我是不是很愚蠢,错过了一些明显的东西?
最佳答案
更改此:
while (health < 0){
health = 0;
document.getElementById("demo2").innerHTML = "Game over";
break;
}
function myFunction() {
if (health>0){
health -= Math.floor(Math.random() * 10)+1;
document.getElementById("hpcount").innerHTML = health;
}
}
对此:
function myFunction() {
// if health is above 0, game is still active
if (health>0){
// generate a new health value
health -= Math.floor(Math.random() * 10)+1;
// check if the game should end
if (health <= 0) {
health = 0;
document.getElementById("demo2").innerHTML = "Game over";
} else {
document.getElementById("hpcount").innerHTML = health;
}
}
}
当您学习 Javascript 时,请考虑熟悉 jQuery ,简化了 javascript 的使用并处理跨浏览器/设备兼容性问题。
关于javascript - 如果 Javascript 中的变量低于零,则使用 while 循环显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25594501/