动态填充表的求和值

时间:2013-07-26 17:17:47

标签: javascript html math drop-down-menu selectedindex

我正在寻找一种方法来对通过引用全局数组的下拉菜单动态添加到表中的列值进行求和。下面是我编写的代码,以下是功能示例的链接:jsFiddle。我是JavaScript的新手,我所知道的一切都是我自己教的,所以请耐心等待,并提前感谢您的帮助。

<!DOCTYPE html>
<html>
    <head>
        <title> </title>
        <script> 
            var x= ["",1,2,3,4,5,6,7,8,9,10];
            var y= ["",4,6,3,4,5,6,7,8,9,10];
            var z= ["",1,2,3,4,5,6,7,8,9,10];
    </script>
     <script>
       function fill(){
            var si= document.getElementById('ddone').selectedIndex;
            if (si!==0){
                var a= x[si];
                var b= y[si];
                document.getElementById('one').innerHTML=a;
                document.getElementById('two').innerHTML=b;
            }};   
        </script>
        <script>
        function fill2(){
            var si2= document.getElementById('ddtwo').selectedIndex;             
            if(si2!==0){
                var c=z[si2];
                var d=z[si2];
                document.getElementById('three').innerHTML=c;
                document.getElementById('four').innerHTML=d;
            }};
        </script>
        <script>
            function total(){
                var w= parseInt(document.getElementById('one').value,10);
                var x= parseInt(document.getElementById('two').value,10);
                var y=parseInt(document.getElementById('three').value,10);
                var z= parseInt(document.getElementById('four').value,10);
                document.getElementById('five').innerHTML=w+y;
                document.getElementById('six').innerHTML=x+z;
};
        </script>
    </head>
    <body>
<select id='ddone' onchange= 'fill()'>
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>
<select id='ddtwo' onchange='fill2()'>
    <option></option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
</select>
<table border=1px width=25%>
    <tr>
        <td id='one'></td>
        <td id='two'></td>
    </tr>
    <tr>
        <td id='three'></td>
        <td id='four'></td>
    </tr>
    <tr>
        <td id='five'></td>
        <td id='six'></td>
    </tr>
</table>
<button id='button' onclick='total()'>total</button>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

将整数提取为总和的方式看起来不正确。如果您想在td元素中获取文字,请尝试innerText,如下所示:

parseInt(document.getElementById('one').innerText,10)

答案 1 :(得分:0)

value切换为innerHTML,您的代码将完美运行。请参阅此小提琴以获取证据:http://jsfiddle.net/Nt9nC/7/