9

我需要提示访问者输入 1 到 100 之间的整数并继续提示,直到输入有效数字。

这是我所拥有的:

<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>

它可以识别号码,但在号码错误时无法重新询问。你能帮我解释一下你添加了什么吗?

非常感谢。

4

4 回答 4

10

这样的事情应该可以解决问题:

do{
    var selection = parseInt(window.prompt("Please enter a number from 1 to 100", ""), 10);
}while(isNaN(selection) || selection > 100 || selection < 1);
于 2013-02-24T00:02:17.467 回答
2

这是一种递归方法:

var number = (function ask() {
  var n = prompt('Number from 1 to 100:');
  return isNaN(n) || +n > 100 || +n < 1 ? ask() : n;
}());
于 2013-02-24T00:09:38.813 回答
1

另一种方法:

<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>
于 2013-02-24T00:15:21.953 回答
0
 function myFunction(id) {

        let person = prompt("Please Enter Your Quotation");
        if (person != null) {
            if(person>=0||person<0){
                alert("max");
            }else{
            alert('Only Number is Allowed');
            myFunction(id)
            }
        }
    }
于 2021-12-23T09:37:00.993 回答