Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用jQuery对表中选定的行求和?_Javascript_Jquery - Fatal编程技术网

Javascript 如何使用jQuery对表中选定的行求和?

Javascript 如何使用jQuery对表中选定的行求和?,javascript,jquery,Javascript,Jquery,有一张桌子 SUM | <input type="text"> | <input type="text"> | | <input type="text"> | <input type="text"> | | <input type="text"> | <input type="text"> | SUM | <input type="text"> | <input type="text">

有一张桌子

SUM | <input type="text"> | <input type="text"> |
    | <input type="text"> | <input type="text"> |
    | <input type="text"> | <input type="text"> |
SUM | <input type="text"> | <input type="text"> |
    | <input type="text"> | <input type="text"> |
FOO | <input type="text"> | <input type="text"> |
BAR | <input type="text"> | <input type="text"> |
它应该是动态的,所以当更多的行出现时,它会自动添加更多的行。

试试看

$('tr.sumToUp input').change(function(){
    var $this = $(this), $row = $this.closest('tr'), $sum = $row.prevAll('.sumToMe').first(), $rows = $sum.nextUntil('.sumToMe', '.sumToUp'), index = $this.closest('td').index();

    var sum = 0;
    $rows.each(function(){
        var val = $(this).find('td').eq(index).find('input').val();
        sum += (+val);
    })
    $sum.find('td').eq(index).find('input').val(sum);
});

演示:

它应该汇总到下一个汇总行,对吗?为什么不添加一个类(例如
class=“sumCell”
)使用jQuery选择这些单元格,并在值发生变化时求和?@DavidHoerster,因为我不知道如何确定要求和到第一个单元格还是第二个单元格。所以在你的小提琴中,将有两个和,每个和等于(8个单元格*3行)对吗?试试看
$('tr.sumToUp input').change(function(){
    var $this = $(this), $row = $this.closest('tr'), $sum = $row.prevAll('.sumToMe').first(), $rows = $sum.nextUntil('.sumToMe', '.sumToUp'), index = $this.closest('td').index();

    var sum = 0;
    $rows.each(function(){
        var val = $(this).find('td').eq(index).find('input').val();
        sum += (+val);
    })
    $sum.find('td').eq(index).find('input').val(sum);
});