js和jquery求table的列和

js实现

<html>
<head>
    <title>求列和</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body onload="sum()">
<table id="ddd">
    <tr><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>2</td><td>3</td><td>4</td></tr>
</table>
<script language="javascript" type="text/javascript">
    function sum(){
        var second = 0;
        var third = 0;
        var trObj = document.getElementsByTagName('tr');
        for(var i = 1; i<=trObj.length; i++){
                for(var j =1;j<=trObj[i-1].getElementsByTagName('td').length;j++)   {
                    if(j%2==0)
                        second+=parseInt(trObj[i-1].getElementsByTagName('td')[j-1].innerHTML);
                    if(j%3==0)
                        third+=parseInt(trObj[i-1].getElementsByTagName('td')[j-1].innerHTML);
                }
        }
        alert("第二列和为:"+second);
        alert("第三列和为:"+third);
    }
</script>
</body>
</html>

jquery实现

<!DOCTYPE html>
<html>
<head>
    <title>求列和</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="js/jquery-1.3.2.min.js"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function(){
            var second=0;
            var third=0;
           // $("tr td:nth-child(2)")    ;
            $("tr td:nth-child(2)").each(function (i){
                   second+=parseInt($(this).html());
            });
            $("tr td:nth-child(3)").each(function(i){
                third+=parseInt($(this).html());
            });
            alert("第二列和为"+second);
            alert("第三列和为"+third);
        });
    </script>
</head>
<body>
<table id="ddd">
    <tr><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>2</td><td>3</td><td>4</td></tr>
    <tr><td>2</td><td>3</td><td>4</td></tr>
</table>
</body>
</html>

 

posted on 2013-01-31 21:26  李超@hicc  阅读(2882)  评论(0编辑  收藏  举报

导航