在收到有效输入之前,如何继续使用JavaScript if?else if语句?

时间:2011-08-05 18:39:44

标签: javascript control-structure

如何使用if ... else if语句继续提示用户提供有效的响应?我的脚本目前只运行一次,但随后中断:

var enterNum = prompt("Please enter a number between 1 and 100", "");


if (isNaN(enterNum)){
    enterNum = prompt("You did not enter a valid number. Please try again", "")
}
else if (enterNum < 1 || enterNum >100){
    enterNum = prompt("Your number is not between 1 and 100. Please try again", "")
}
else{
    document.write("Your number is ", enterNum)
}

提前致谢!

5 个答案:

答案 0 :(得分:9)

var enterNum = prompt("Please enter a number between 1 and 100", "");

while(isNaN(enterNum) || enterNum < 1 || enterNum >100) {
    enterNum = prompt("You did not enter a valid number. Please try again", "")
}
document.write("Your number is ", enterNum)

答案 1 :(得分:1)

你不能只用if / else。使用循环。例如:

var enterNum = prompt("Please enter a number between 1 and 100", "");
while(true)
{
  if (isNaN(enterNum)){
      enterNum = prompt("You did not enter a valid number. Please try again", "")
  }
  else if (enterNum < 1 || enterNum >100){
      enterNum = prompt("Your number is not between 1 and 100. Please try again", "")
  }
  else
    break;
}
document.write("Your number is ", enterNum)

答案 2 :(得分:1)

var valid = false;
var msg = "Please enter a number between 1 and 100";

while(!valid){
    var enterNum = prompt(msg, "");

    if (isNaN(enterNum)){
        msg = "You did not enter a valid number. Please try again";
    }
    else if (enterNum < 1 || enterNum >100){
        msg = "Your number is not between 1 and 100. Please try again";
    }
    else{
        valid = true;
        document.write("Your number is ", enterNum)
    }
}

还有很多其他方法可以做类似的事情,有些取决于风格。这是为了便于阅读。也可以消除valid变量,输入正确后只需while(true)然后breakdocument.write也可能在一段时间之后。

答案 3 :(得分:0)

答案 4 :(得分:-1)

我讨厌javascript所以我的语法可能已关闭但是类似于:

var isValid = false;
var message = "Please enter a number between 1 and 100";

while(isValid == false)
{
    var enterNum = prompt(message, "");

    if (isNaN(enterNum)){
        isValid = false;
        message = "You did not enter a valid number. Please try again";
    }
    else if (enterNum < 1 || enterNum >100){
        isValid = false;
        message = "Your number is not between 1 and 100. Please try again";
    }
    else{
        isValid = true;
        document.write("Your number is ", enterNum)
    }
}

使用do / while循环可能有点整洁。