尝试限制猜测后javascript(html)while循环不起作用

我的主要目的是如果用户猜中数字 5 次或当用户猜对正确答案时停止程序,程序也应该结束。


function abc()

{

    var guessbutton = document.getElementById("guessbutton");

    var guess = document.getElementById("guess").value;

    var maxtries = 5;

    var count = 0;

var secret = 10;

    

while (count < 6)

{


if (guess == secret) 

{

document.getElementById("feedback").innerHTML = "correct";

guessbutton.disabled=true;

break;

}

else if (guess > secret) 

{

document.getElementById("feedback").innerHTML = "too high";

}

else if (guess < secret) 

{

document.getElementById("feedback").innerHTML = "too low";

}


else

{document.getElementById("feedback").innerHTML = "max try";

guessbutton.disabled=true;

break;

}

count++;

}

}

我在使用这段代码时遇到的问题是,即使经过 5 次尝试,它仍会继续。我假设错误是由于count++;无法正常工作


这是我的 html 代码


<input id="guess" type="text" name="guess">

<button id="guessbutton" type="button" onclick="return abc()">Guess</button>

<p id="feedback"></p>


森林海
浏览 100回答 1
1回答

慕哥9229398

您需要摆脱 while 循环。您只是循环而不允许用户更新输入文本框。您应该检查每次点击的次数。var guessbutton = document.getElementById("guessbutton");var count = 0;var maxTries = 5;var secret = 10;function abc() {&nbsp; var guess = Number(document.getElementById("guess").value);&nbsp; count++;&nbsp; console.log(count);&nbsp; if (guess == secret) {&nbsp; &nbsp; document.getElementById("feedback").innerHTML = "correct";&nbsp; &nbsp; guessbutton.disabled = true;&nbsp; } else if (guess > secret) {&nbsp; &nbsp; document.getElementById("feedback").innerHTML = "too high";&nbsp; } else if (guess < secret) {&nbsp; &nbsp; document.getElementById("feedback").innerHTML = "too low";&nbsp; }&nbsp;&nbsp; if (count >= maxTries) {&nbsp; &nbsp; document.getElementById("feedback").innerHTML = "max try";&nbsp; &nbsp; guessbutton.disabled = true;&nbsp; }}<input id="guess" type="text" name="guess"><button id="guessbutton" type="button" onclick="return abc()">Guess</button><p id="feedback"></p>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript