jquery实现table列求和

<table id="mytable" border="1" width="37%">
<thead>
    <tr>
        <td width="63">ID</td>
        <td width="68">字段1</td>
        <td width="62">字段2</td>
        <td width="75">字段3</td>
        <td>字段4</td>
    </tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td width="63">11</td>
        <td width="68">12</td>
        <td width="62">13</td>
        <td width="75">14</td>
    </tr>
    <tr>
        <td>2</td>
        <td width="63" >22</td>
        <td width="68" >26</td>
        <td width="62" >28</td>
        <td width="75" >27</td>
    </tr>
</tbody>
<tfoot>
    <tr id="totalRow">
        <td>合计</td>
        <td width="63"></td>
        <td width="68"></td>
        <td width="62"></td>
        <td width="75"></td>
    </tr>
</tfoot>
</table>
var sum = new Array(+$('#mytable thead tr td:not(:first-child)').length).fill(0);

$('#mytable tbody tr').each(function() {
    $(this).children('td:not(:first-child)').each(function() {
        var index = $(this).index() - 1;

        sum[index] += +$(this).text();
    });
});

$('#mytable #totalRow td:not(:first-child)').each(function() {
    var index = $(this).index() - 1;

    $(this).text(sum[index]);
});

这里有几个知识点:

new Array()构造新数组

.fill()填充数组

选择器:not()和:first-child的用法

字符串或者数字前面加+强转成数字

赋值运算符+=的使用

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值