JavaScript求和


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>求和</title>
    <script>
        window.onload=function(){
            var oTxt1=document.getElementById('txt1');
            var oTxt2=document.getElementById('txt2');
            var oBtn=document.getElementById('btn1');
            oBtn.onclick=function(){
                alert(parseInt(oTxt1.value)+parseInt(oTxt2.value));
            }
        }
    </script>
</head>
<body>
<input id="txt1" type="text"/>
<input id="txt2" type="text"/>
<input id="btn1" type="button" value="求和">

</body>
</html>

 

NaN:not a number不是数字

12+NaN=NaN

NaN!=NaN

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>NaN</title>
</head>
<script>
    var a=parseInt('abc');
    var b=parseInt('def');
    alert(a==b);
</script>
<body>
</body>
</html>

 

 判断是否是NaN

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nan</title>
<script>
    var a=parseInt('abc');
    alert(isNaN(a));
</script>
</head>
<body>

</body>
</html>

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>求和</title>
    <script>
        window.onload=function() {
            var oTxt1 = document.getElementById('txt1');
            var oTxt2 = document.getElementById('txt2');
            var oBtn= document.getElementById('btn1');

            oBtn.onclick=function(){
                var n1=parseInt(oTxt1.value);
                var n2=parseInt(oTxt2.value);
                if(isNaN(n1)){
                    alert('您输入的第一个数字有误');}

                else if(isNaN(n2)){
                        alert('您输入的第二个数字有误');
                    }
                else{
                alert(n1+n2);
            }
        }
        }
    </script>
</head>
<body>
<input id="txt1" type="text"/>
<input id="txt2" type="text"/>
<input id="btn1" type="button" value="求和">

</body>
</html>

FLOAT

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    var a='3.5';
    //alert(parseInt(a));
    alert(parseFloat(a));
</script>
</body>
</html>

 

 

 

posted @ 2016-10-27 14:20  缘琪梦  阅读(5791)  评论(1编辑  收藏  举报