gpt4 book ai didi

javascript - 猜谜游戏可能存在语法错误

转载 作者:行者123 更新时间:2023-11-30 14:02:27 26 4
gpt4 key购买 nike

我创建了一个数字猜谜游戏,您作为用户输入一个数字,并尝试获得计算机选择的相同数字。计算机会选择 1-100 之间的一个数字,每次您猜它都会告诉您是否需要猜测更高或更低的数字。

问题出在 java 脚本上,我正在考虑是我写错了什么还是不应该是什么东西。我已经检查了所有 ID 和所有内容,但我仍然没有从代码中获得任何反馈。

我希望代码在我尝试按下猜测按钮时输出一些内容

<!DOCTYPE html>

<html>

<head>
<title>GuessingGame</title>
<style>

</style>
<script>
var playerGuess = document.getElementById("guessInput").value;
var computerGuess = Math.floor(Math.random() * 10 + 1);
var playAgain = true;

function randNum(low, high) {
var number = Math.floor(Math.random() * high + low);
return number
}

function guessNumber() {
if (playerGuess > computerGuess) {
document.getElementById("output").innerHTML =
"Guess lower"
} else if (playerGuess < computerGuess) {
document.getElementById("output").innerHTML =
"Guess higher"
} else(playerGuess == computerGuess) {
document.getElementById("output").innerHTML =
"Good job you guessed right"
}
</script>
</head>

<body>
<h1>Guessing Game</h1>
<h2>The computer will choose a number between 1 and 100</h2>
<h2>You have to try and guess what it picked</h2>
<span><input type="number" id="guessInput">
<button onclick="guessNumber();">Guess</button><button
onClick="reset();">Reset</button>
<p id="output"></p>

</body>

</html>

最佳答案

你的一些javascript代码写错了,你的一些HTML是无效的。在这里,我已将变量从全局范围移至函数,因为将其移至此处更有意义,并且每次单击按钮时变量都会发生变化,而不仅仅是加载:

<!DOCTYPE html>
<title>GuessingGame</title>
<html>
<body>
<h1>Guessing Game</h1>
<h2>The computer will choose a number between 1 and 100</h2>
<h2>You have to try and guess what it picked</h2>
<span><input type="number" id="guessInput"/></span>
<button onclick="guessNumber();">Guess</button>
<button onClick="reset();">Reset</button>
<p id="output"></p>
</body>
<script>
var computerGuess = Math.floor(Math.random() * 10 + 1);
var playAgain = true;

function randNum(low,high) {
var number = Math.floor(Math.random()*high+low);
return number
}
function guessNumber(playerGuess) {
var playerGuess = document.getElementById("guessInput").value;
if (playerGuess > computerGuess) {
document.getElementById("output").innerHTML = "Guess lower"
} else if (playerGuess < computerGuess) {
document.getElementById("output").innerHTML = "Guess higher"
} else {
document.getElementById("output").innerHTML = "Good job you guessed right"
}
}
</script>
</html>

您需要为按钮编写reset() 函数来执行任何操作:)

关于javascript - 猜谜游戏可能存在语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com