需要帮助行javascript中的数字总和

时间:2015-10-26 20:09:29

标签: javascript

<html>
    <script>
        function myFunction() {
            var a = document.getElementById("a").value;
            var b = document.getElementById("b").value;
            var c = document.getElementById("c").value;
            var d = document.getElementById("d").value;
            var erg = document.getElementById("erg").value;
            var sum = a + b + c + d;
            document.getElementById("erg").innerHTML = sum;
    </script>
    <body>
        <table border="1">
            <tr>
                <td id="a">2</td>
                <td id="b">4</td>
                <td id="c">5</td>
                <td id="d">3</td>
                <td id="erg"></td>
                <td>
                    <button type="button" onclick="myFunction()">Sum</button>
                </td>
            </tr>
        </table>
    </body>
</html>

1 个答案:

答案 0 :(得分:2)

解析数字, 并且td没有值,请使用innertext

<html>
    <script>
        function myFunction() {
            var a =parseInt(document.getElementById("a").innerText);
            var b = parseInt(document.getElementById("b").innerText);
            var c = parseInt(document.getElementById("c").innerText);
            var d = parseInt(document.getElementById("d").innerText);
            
            var sum = a + b + c + d;
            document.getElementById("erg").innerHTML = sum;
          }
    </script>
    <body>
        <table border="1">
            <tr>
                <td id="a">2</td>
                <td id="b">4</td>
                <td id="c">5</td>
                <td id="d">3</td>
                <td id="erg"></td>
                <td>
                    <button type="button" onclick="myFunction()">Sum</button>
                </td>
            </tr>
        </table>
    </body>
</html>