这个数字脚本出了什么问题



我是JavaScript的新手,我想做一个输入检查。这是我的脚本:

function checkInp()
{
  var x=document.forms["myForm"]["num"].value; // Get the value
  if (isNaN(x)) 
  {
    alert("Not a number!"); // Check if the input is a number
    return false;
  }
  var valuex=document.forms["myForm"]["num"].value; // Get the value, i don't know if i have to re-write this variable, if no, please comment.
  Number(valuex); // Make the input a number
  if (valuex.value > 480) {
    alert("Too high!"); // See if the number is greater than 480. If yes, say that, if not, return normally.
    return false;
  } 
  else {
    return;
  }
}

我不知道会发生什么,但自从我添加了第二部分(检查数字是否大于480)后,脚本就不起作用了
请帮助我,如果可能的话,举一个完整的例子。

如果我没有错,我认为你只需要这样做:

If(valuex > 480)..

我的做法:

  • 文档选择器查询更容易理解
  • 不要多次获取值
  • 使用ParseInt转换数字上的var
  • 如果成功,不要忘记回报真实

代码:

function checkInp() {
  var x = document.querySelector('input[name="num"]').value;  
  if (isNaN(x)) {
    alert("Must be a number");
    return false
  } else if (x > 480) {
    alert("Must be under 480");
    return false
  }
  return true
}

最新更新