<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
        <title>无标题</title>
        <script type="text/javascript">
        function sum(obj) {
            var a = document.getElementById("a");
            var b = document.getElementById("b");
            var s = document.getElementById("sum");
            if(a.value === "" || b.value === "") {
                return;
            } 
            s.value = parseInt(a.value) + parseInt(b.value);
        }
        </script>
    </head>
    <body>
        <input type="text" id="a" onkeyup="sum(this);" />
        <input type="text" id="b" onkeyup="sum(this);" />
        <input type="text" id="sum" />
    </body>
</html>可以2+2=4,但是如果是1.2+2.4就不行。如何改为可以小数点整数相加的?

解决方案 »

  1.   


    <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
            <title>无标题</title>
            <script type="text/javascript">
            function sum(obj) {
                var a = document.getElementById("a");
                var b = document.getElementById("b");
                var s = document.getElementById("sum");
                if(a.value === "" || b.value === "") {
                    return;
                } 
                s.value = Math.round( (parseFloat(a.value) + parseFloat(b.value) ) * 1000 ) / 1000 ;
            }
            </script>
        </head>
        <body>
            <input type="text" id="a" onkeyup="sum(this);" />
            <input type="text" id="b" onkeyup="sum(this);" />
            <input type="text" id="sum" />
        </body>
    </html>
      

  2.   

    s.value = parseInt(a.value) + parseInt(b.value);这句改下   你去查下parseInt是什么意思吧
    s.value = a.value*1 + b.value*1
      

  3.   

    parseInt是转为整数
      

  4.   

    parseInt 换成 parseFloat