javascript javascript提示编号,如果回答错误继续提示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15047140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript prompt number and continue prompting if answer is wrong
提问by Art
I need prompt the visitor for an integer between 1 and 100 and to continue promptinguntil a valid number is entered.
我需要提示访问者输入 1 到 100 之间的整数,并继续提示直到输入有效数字。
Here is what I have:
这是我所拥有的:
<script>
var number = parseInt(prompt("Please enter a number from 1 to 100", ""));
if (number < 100) {
document.write("Your number (" + number + ") is matches requirements", "");
} else if (isNaN(number)) {
parseInt(prompt("It is not a number. Please enter a number from 1 to 100", ""));
} else {
parseInt(prompt("Your number (" + number + ") is above 100. Please enter a number from 1 to 100", ""));
}
</script>
It recognizes the number but fails to re-ask when the number is wrong. Can you please help me and explain what you added?
它可以识别号码,但在号码错误时无法重新询问。你能帮我解释一下你添加了什么吗?
Thank you very much.
非常感谢你。
回答by Rob M.
Something like this should do the trick:
像这样的事情应该可以解决问题:
do{
var selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10);
}while(isNaN(selection) || selection > 100 || selection < 1);
回答by elclanrs
Here's a recursive approach:
这是一种递归方法:
var number = (function ask() {
var n = prompt('Number from 1 to 100:');
return isNaN(n) || +n > 100 || +n < 1 ? ask() : n;
}());
回答by Nishanth Nair
Another approach:
另一种方法:
<html>
<head> </head>
<body onload="promptForNumber();">
<script>
function promptForNumber( text)
{
if(text == '' ){
text = "Please enter a number from 1 to 100";
}
var number = parseInt(window.prompt(text, ""));
checkNumber(number);
}
function checkNumber(number){
if (number <= 100 && number >= 1) {
document.write("Your number (" + number + ") matches requirements", "");
} else if (isNaN(number)) {
promptForNumber("It is not a number. Please enter a number from 1 to 100", "");
} else {
promptForNumber("Your number (" + number + ") is not between 1 and 100", "");
}
}
</script>
</body>
</html>