如何继续执行 JavaScript if.. else if 语句,直到收到有效输入?
如何使用 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)
}
提前致谢!
How can I continue prompting a user for a valid response using if... else if statements? My script currently works once, but then breaks:
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)
}
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
还有很多其他方法可以完成类似的事情,具体取决于风格。这是为了可读性。还可以消除
valid
变量,只需使用while(true)
,然后在输入正确后break
。document.write
也可能会在一段时间之后。There are a bunch of other ways to do a similar thing, somewhat depending on style. This went for readability. Could also eliminate the
valid
variable and simply havewhile(true)
thenbreak
once the input is correct. Thedocument.write
could also be after the while.你不能只用 if/else。使用循环。例子:
You can't with only if/else. Use a loop. Example:
使用 while 循环
http://help.dottoro.com/ljqepqhd.php#dowhile
或
http://help.dottoro.com/ljqepqhd.php#while
use a while loop instead
http://help.dottoro.com/ljqepqhd.php#dowhile
or
http://help.dottoro.com/ljqepqhd.php#while
我讨厌 javascript,所以我的语法可能是关闭的,但类似:
使用 do/while 循环可能会更整洁一些。
I hate javascript so my syntax is probably off but something like:
Using a do/while loop might be a little neater.