JavaScript简单的“错误处理”,用条件替换NaN

时间:2010-10-12 04:25:43

标签: javascript error-handling nan

我想知道如何检测错误输入类型,而不是向用户呈现NaN,而是显示一条逻辑信息。

这是我的代码:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>

<script>
window.onload = function() {
    document.getElementById('calculate').onclick = function calculateQuad()
    {
        var inputa = document.getElementById('variablea').value;
        var inputb = document.getElementById('variableb').value;
        var inputc = document.getElementById('variablec').value;

        root = Math.pow(inputb,2) - 4 * inputa * inputc;
        root1 = (-inputb + Math.sqrt(root))/2*inputa
        root2 = (-inputb + Math.sqrt(root))/2*inputa 

        document.getElementById('root1').value = root1;
        document.getElementById('root2').value = root2;
        if(root<'0')
        {
            document.getElementById('root1').value = 'No real solution'
            document.getElementById('root2').value = 'No real solution'
        }
        else {
            if(root=='0')
            {
                document.getElementById('root1').value = root1
                document.getElementById('root2').value = 'No Second Answer'
            }
            else {
                document.getElementById('root1').value = root1
                document.getElementById('root2').value = root1
                }
            }
    };
    document.getElementById('erase').onclick = function()
    {
        document.getElementById('form1').reset();
    }
}
</script>

<style>
#container
{
    text-align: center;
}
</style>

</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    a:<input id="variablea" value="" type="text">
    <br/>
    b:<input id="variableb" value="" type="text">
    <br />
    c:<input id="variablec" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

所以,比如说你在b输入字段输入10a,但a = 1c = 0我希望能够检测到不正确的输入,并打印“请仅限输入整数“或沿着那些方向的东西。

3 个答案:

答案 0 :(得分:1)

这很简单,这是一个完整的示例,输出漂亮的错误信息到;)

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Quadratic Root Finder</title>

<script>
function getnum( id )
{   // get 'n' check number
    var input = +(document.getElementById(id).value);
    if ( isNaN( input ) )
    {
        document.getElementById('errmsg').innerHTML = 'Value of <em>' + id +'</em> is non-numeric, please enter a number.';
        return false;
    }
    return input;
}

window.onload = function() {
    document.getElementById('calculate').onclick = function calculateQuad()
    {
        var inputa = getnum('variable a');
        var inputb = getnum('variable b');
        var inputc = getnum('variable c');

        if ( inputa === false )
            return;
        if ( inputb === false )
            return;
        if ( inputb === false )
            return;

        root = Math.pow(inputb,2) - 4 * inputa * inputc;
        root1 = (-inputb + Math.sqrt(root))/2*inputa;
        root2 = (-inputb + Math.sqrt(root))/2*inputa;

        document.getElementById('root1').value = root1;
        document.getElementById('root2').value = root2;
        if(root < 0)
        {
            document.getElementById('root1').value = 'No real solution';
            document.getElementById('root2').value = 'No real solution';
        }
        else {
            if(root==0)
            {
                document.getElementById('root1').value = root1;
                document.getElementById('root2').value = 'No Second Answer';
            }
            else {
                document.getElementById('root1').value = root1;
                document.getElementById('root2').value = root1;
                }
            }
    };
    document.getElementById('erase').onclick = function()
    {
        document.getElementById('form1').reset();
    }
}
</script>

<style>
#container
{
    text-align: center;
}
#errmsg
{
    color: #c00;
}
</style>

</head>

<body>
<div id="container">
<h1>Quadratic Root Finder!</h1>
<form id="form1">
    <span id="errmsg"></span><br/>
    a:<input id="variable a" value="" type="text">
    <br/>
    b:<input id="variable b" value="" type="text">
    <br />
    c:<input id="variable c" value="" type="text">
    <br />
    <input id="calculate" value="Calculate!" type="button">
    <input id="erase" value="Clear" type="button">
    <br />
    <br />
    Roots:
    <br />
    <input id="root1" type="text" readonly>
    <br />
    <input id="root2" type="text" readonly>
</form>
</div>
</body>
</html>

答案 1 :(得分:0)

您可以在尝试在计算中使用输入之前检查输入。

document.getElementById('calculate').onclick = function calculateQuad() {
    var inputa = document.getElementById('variablea').value;
    var inputb = document.getElementById('variableb').value;
    var inputc = document.getElementById('variablec').value;

    inputa = new Number(inputa); // try to convert to number
    if (isNaN(inputa)) { // use built in method to check for NaN
        alert('variable a is not a valid integer or whatever.');
        return;
    }

    // TODO repeat for b and c

    root = Math.pow(inputb, 2) - 4 * inputa * inputc;
    root1 = (-inputb + Math.sqrt(root)) / 2 * inputa; // don't forget your semicolons.
    root2 = (-inputb + Math.sqrt(root)) / 2 * inputa;

    document.getElementById('root1').value = root1;
    document.getElementById('root2').value = root2;

    // should be comparing against integer 0, not string 0
    if (root < 0) {
        document.getElementById('root1').value = 'No real solution'
        document.getElementById('root2').value = 'No real solution'
    }
    else {
        if (root === 0) {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = 'No Second Answer'
        }
        else {
            document.getElementById('root1').value = root1
            document.getElementById('root2').value = root1
        }
    }
};

答案 2 :(得分:0)

我认为你需要这样的东西

    function NaNValueReplacement() {
for (var i = 0; i < arguments.length; i++) {
    //alert(arguments[i]);
      var x = (arguments[i]);
      var y = document.getElementById(x).value; 
      var y_txtField = document.getElementById(x);
   /*
   alert('Argument '+i+'  with name "'+x+'"   :::   Value of element '+i+' is "'+y+'"   and the variable type is "'+y_txtField+'"');
   */
     if ( isNaN(y))
    {
        y_txtField.value='Some Other Value';

    }

}}

并称之为: NaNValueReplacement('txt_field_1','txt_field_2','txt_field_3','txt_field_4');

您可以根据需要放置任意数量的txt_fields。

此外,我在此处放置了一个示例http://jsfiddle.net/lidakis/mveWy/6/

希望它有所帮助。