2 回答
TA贡献2039条经验 获得超7个赞
您的问题是,当您使用var关键字时,您正在创建一个新变量。您应该删除varif 和 else的内部。这将允许您更改外部attempts变量,而不是您使用var.
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
console.log("Attempts is: "+attempts);
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
我想我明白你有什么问题。您期望已记录到控制台的内容在变量更改时发生更改。事情不是这样的console.log
。它只记录变量的当前值。如果您想查看新值,您应该再次记录它,在这种情况下,在每次猜测之后。
TA贡献1871条经验 获得超8个赞
每次单击时,您都在定义一个变量。从 if/else 块中删除“var”
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
<script type="text/javascript">
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
}
</script>
添加回答
举报