用户输入进行错误检查

时间:2018-06-07 20:29:16

标签: javascript for-loop error-handling

我无法通过验证用户输入来验证错误。它工作正常,直到我尝试添加错误检查,因为范围应该是1-10。我知道我可以将HTML中的输入框设置为该范围,但对于此分配,如果超出该范围,我们应该使用错误消息。我只是在寻求帮助,以了解我在哪里出错了。谢谢!

这是我的编码:



function OddNumber() {
  var x = parseFloat(document.getElementById('input').value);
  try {
    if (x < 1 || x > 10)
  } //less than 1 or greater than 10 creates an error (in theory)
  catch (err) {
    document.getElementById("output").innerHTML = err.name;
  } else {
    for (var i = 1; i <= x; i++) { //gets input from user and loops to find odd numbers between 1 and that number
      if (i % 2 != 0) {
        document.getElementById("output").innerHTML = (i + " ");
      }
    }
  }
&#13;
<h1>Odd Number Generator</h1>

<p>Enter a number between 1 and 10, then click "Submit" to get the odd numbers between 1 and the number you entered.</p>

<p>Number: <input type="number" id="input" name="input"></p>
<p><button onclick="OddNumber()">Submit</button>
  <p id="output"></p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

您的问题在于:

if(x < 1 || x > 10) } //less than 1 or greater than 10 creates an error (in theory)
    catch(err) {

if语句后面没有任何内容,如果方括号正确排列则更容易看到。而且你不需要尝试/捕获这种错误检查。

<script>
function OddNumber () {
    var x = parseFloat(document.getElementById('input').value);
    if(x < 1 || x > 10) { //less than 1 or greater than 10 creates an error (in theory)
        document.getElementById("output").innerHTML = "Your error string";
    } else {
        for (var i = 1; i <= x; i++) { //gets input from user and loops to find odd numbers between 1 and that number
            if (i % 2 != 0) {
                document.getElementById("output").innerHTML = (i + " ");
            }
        }
    }
}
</script>

答案 1 :(得分:0)

只需检查if(x < 1 || x > 10)不会抛出错误。如果您需要使用catch块进行分配,则需要{if}中的throw new Error()。虽然根本不需要它。

另外我认为你的意思是在innerHTML上使用+=运算符。

&#13;
&#13;
function OddNumber () {
    var x = parseFloat(document.getElementById('input').value);
    if(x < 1 || x > 10){
          
      document.getElementById("output").innerHTML = "invalid number";  
    } //less than 1 or greater than 10 report error
    else {
        for (var i = 1; i <= x; i++) { //gets input from user and loops to find odd numbers between 1 and that number
          if (i % 2 != 0) {
           document.getElementById("output").innerHTML += (i + " ");
          }
        }
    }
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Odd Number Generator</title>
<meta Charset="utf-8">
</head>
<h1>Odd Number Generator</h1>

<body>



<p>Enter a number between 1 and 10, then click  "Submit" to get the odd numbers between 1 and the number you entered.</p>


  <p>Number: <input type="number" id="input" name="input"></p>
  <p><button onclick="OddNumber()">Submit</button>
  <p id="output"></p>





</body>
</html>
&#13;
&#13;
&#13;