簡體   English   中英

如何在 JS 中單擊取消時關閉提示?

[英]How do I close a prompt upon clicking cancel in JS?

我一生都無法弄清楚如何在我的代碼中按取消進行猜謎游戲時完全關閉提示。 我已經嘗試了幾件事,但每次代碼都會忽略我正在嘗試做的事情,或者以錯誤結束。 這是有問題的代碼:

let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`);
let num = (4);

let numTries = 1

console.log(numGuess);

numGuess = parseInt(numGuess)

if (prompt == null) {

alert (`Press F5 to play again.`) 


}
if (numGuess === num) {

  alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`);

}

else while ((numGuess !== num) && (numTries <3))

{

  numTries = numTries++

  alert (`Incorrect guess. Try again.`)

}

檢查用戶輸入值,而不是提示。 並且也不要在這里使用while循環。循環用於遍歷。

 let numGuess = prompt (`Guess the number I am thinking of (between 1 and 10):`); let num = (4); let numTries = 1 console.log(numGuess); numGuess = parseInt(numGuess) if (!numGuess) { alert (`Press F5 to play again.`) } else if (numGuess === num) { alert (`Correct! You guessed the number in 1 try! Press F5 to play again.`); } else{ numTries = numTries++ alert (`Incorrect guess. Try again.`) }

您的代碼的主要問題是在 numTries 之后使用“++”,這使得 numTries 變量值不會改變並且 while 循環繼續工作而不會停止,您需要在之前插入它。 前任:

++numTries

下面的代碼是您想要做的工作示例。

 let numGuess; let numTries = 0; let num = 4; const guessFunction = () => { if (numTries >= 3) { alert("Sorry you Failed in the 3 tries! Press F5 to play again."); return; } numGuess = parseInt( prompt(`Guess the number I am thinking of (between 1 and 10):`) ); numTries = ++numTries if (numGuess === num) { alert(`Correct! You guessed the number in ${numTries} try! Press F5 to play again.`); return; } if(numTries <= 2) { alert(`Incorrect guess. Try again.`); } guessFunction() }; guessFunction()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM