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);
});