2016-07-23 17 views
-2

我对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; 
    } 
} 

我不知道发生了什么,但自从我加入了第二部分的脚本不工作(检查,如果数大于48​​0)。
请帮助我,如果可能,请用完整示例。

+0

你为什么要否决?有理由吗? – MucaP

回答

0

的方式,我会做:

  • 文件selectorQuery是更容易理解
  • 不要多次获得数值
  • 使用ParseInt转换您的变数
  • 不要忘记返回真要是成功

代码:

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 
} 
+0

谢谢。有效! – MucaP

+1

请注意,'parseInt()'用于**整数**,并且它允许尾随非数字垃圾(所以“123hello world”被接受)。 – Pointy

+1

'!0'为真,0肯定是一个数字。最好检查'isNaN(x)'或'x!== x'。 'NaN'是JS中唯一不等于它自己的值 – Thomas

1

,如果我没有错,我thnk你只需要做的是这样的:

If(valuex > 480)..