JavaScript:即使用户输入错误,两个对话框都会显示

时间:2017-04-03 14:04:50

标签: javascript

这是一款简单的JavaScript / HTML猜谜游戏。我唯一的问题是,当用户输入1-6以外的数字/字母时,应该弹出“错误”消息 - 确实如此,但随后游戏继续进行,它仍然会告诉您是否是赢家与否。这是我的代码。

function jsFunc() {
    var number = Math.ceil (Math.random() * 6) + 1;
    var guessNum = 0;
    guessNum = document.getElementById("num").value;

    if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
        alert ("Must be a number between 1 and 6. Please re-enter!");
    }

    if (number == guessNum)
        alert("Congratulations, You Win!!!");
    else
        alert("Aw, You Lose..");
}

3 个答案:

答案 0 :(得分:0)

你应该做其他事 - 如果

function jsFunc() {
var number = Math.ceil (Math.random() * 6) + 1;
var guessNum = 0;

    guessNum = document.getElementById("num").value;

if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
    alert ("Must be a number between 1 and 6. Please re-enter!");
}
else if (number == guessNum)
    alert("Congratulations, You Win!!!");
else
    alert("Aw, You Lose..");
}

答案 1 :(得分:0)

  if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
                alert ("Must be a number between 1 and 6. Please re-enter!");
             }

            else if (number == guessNum)
              {
                alert("Congratulations, You Win!!!");
              }
            else
             {
                alert("Aw, You Lose..");
             }

您是否/ else逻辑需要是一个连续的块。因为在您的原始代码中,您的第二个IF无论如何都会得到评估!

答案 2 :(得分:0)

您可以添加if else以使其正常工作

请参阅代码段

&#13;
&#13;
   function jsFunc() {
            var number = Math.ceil (Math.random() * 6) + 1;
            var guessNum = 0;

                guessNum = document.getElementById("num").value;
               

            if (isNaN(guessNum) || guessNum < 1 || guessNum > 6) {
                alert ("Must be a number between 1 and 6. Please re-enter!");
            }else if (number == guessNum){
                alert("Congratulations, You Win!!!");
                }
            else{
                alert("Aw, You Lose..");
                }
        }
        
 
&#13;
<input id ="num"/> <button  onClick="jsFunc()">Submit</button>
&#13;
&#13;
&#13;