变量 求和

变量类型:number  string   boolean    function   object  undefined

typeof  a          返回a变量所属类型

isNaN() 函数用于检查其参数是否是非数字。

alert(NaN==NaN)   false

input中的value值类型是string,需要类型转换;同时需考虑文本框内所输入的内容是否是数字,加以判断(isNaN);

html代码:

<body>
        <input type="text" id="txt1" />
        <input type="text" id="txt2" />
        <input type="button" name="btn1" id="btn1" value="求和" />
</body>

js代码:

<script type="text/javascript">
            window.onload=function(){
                var oTxt1=document.getElementById("txt1");
                var oTxt2=document.getElementById("txt2");
                var oBtn=document.getElementById("btn1");
                oBtn.onclick=function(){
                    if(isNaN(parseInt(oTxt1.value))){
                        alert("对不起,你输入的第一项内容不符合规范");
                        oTxt1.value="";
                        oTxt2.value="";
                    }else if(isNaN(parseInt(oTxt2.value))){
                        alert("对不起,你输入的第二项内容不符合规范");
                        oTxt1.value="";
                        oTxt2.value="";
                    }else{
                        alert(parseInt(oTxt1.value)+parseInt(oTxt2.value));
                        oTxt1.value="";
                        oTxt2.value="";
                    }
                }
            }
</script>

效果:

原文地址:https://www.cnblogs.com/rain92/p/5673378.html