jQuery sum行添加所有单元格

搜索了有关添加表列的各种SO问题,但在行上没有多少.这是我到目前为止所拥有的:

HTML

<table>
    <thead>
        <tr>
            <th>MAX ATK</th>
            <th>MAX DEF</th>
            <th>MAX HP</th>
            <th>Overall</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td class="combat">8170</td>
            <td class="combat">6504</td>
            <td class="combat">6050</td>
            <td class="total-combat"></td>
        </tr>
        <tr>
            <td class="combat">8500</td>
            <td class="combat">10200</td>
            <td class="combat">7650</td>
            <td class="total-combat"></td>
        </tr>
        <tr>
            <td class="combat">9185</td>
            <td class="combat">7515</td>
            <td class="combat">9185</td>
            <td class="total-combat"></td>
        </tr>
    </tbody>
</table>

jQuery的

$(document).ready(function () {
     var sum = 0;
     $('tr').find('.combat').each(function () {
         var combat = $(this).text();
         if (!isNaN(combat) && combat.length !== 0) {
             sum += parseFloat(combat);
         }
     });

     $('.total-combat').html(sum);
 });

你可以看到我的小提琴here.

问题:它正在查找所有出现的.combat并将它们相加而不是仅查找当前行中出现的.combat.所以代替:

MAX ATK MAX DEF MAX HP  Overall
 8170    6504    6050   20724
 8500    10200   7650   26350
 9185    7515    9185   25885

我越来越:

MAX ATK MAX DEF MAX HP  Overall
 8170    6504    6050   72959
 8500    10200   7650   72959
 9185    7515    9185   72959

我尝试使用nearest()思考,告诉它找到父tr并且只在那个tr中添加tds,如下所示:

$('.combat').closest('tr').each(function () {

但那不起作用:(

任何帮助将不胜感激!

解决方法

你需要使用每个循环
$(document).ready(function () {
    //iterate through each row in the table
    $('tr').each(function () {
        //the value of sum needs to be reset for each row,so it has to be set inside the row loop
        var sum = 0
        //find the combat elements in the current row and sum it 
        $(this).find('.combat').each(function () {
            var combat = $(this).text();
            if (!isNaN(combat) && combat.length !== 0) {
                sum += parseFloat(combat);
            }
        });
        //set the value of currents rows sum to the total-combat element in the current row
        $('.total-combat',this).html(sum);
    });
});

演示:Fiddle

较短的求和方式:使用一元加 – Demo

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...