我有动态增加行和3列,每个单元格包含文本框。我想将前两列的值加到每行的第3列。我怎么能用jquery做到这一点?
让我想象一下:
c1 c2 s
r1 5 6 11
r2 7 3 10
. . . .
s sc1 sc2 sc3
sc1,sc2,sc3是您看到的相关列的总和。
答案 0 :(得分:0)
快速粗略的版本 - 对于每个TR,将其子TD的内容转换为数字并求它们,然后当求和完成时,在末尾弹出一个TD,其值为“sum”作为其文本。
$("tr").each( function() {
var sum = 0;
$("td", $(this)).each( function() {
sum += Number($(this).text());
} );
$(this).append($("<td>").text(sum));
} );
答案 1 :(得分:0)
你应该像这样构建你的表:
<table class="summonizer">
<thead>
<tr>
<th></th>
<th>c1</th>
<th>c2</th>
<th>s</th>
</tr>
</thead>
<tbody>
<tr>
<th>r1</th>
<td><input type="text" value="5"/></td>
<td><input type="text" value="6"/></td>
<td></td>
</tr>
<tr>
<th>r2</th>
<td><input type="text" value="7"/></td>
<td><input type="text" value="3"/></td>
<td></td>
</tr>
</tbody>
<tfoot>
<tr>
<th>s</th>
<td></td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
你的javascript应该是这样的:
function summonize_table($table) {
var col_sums = [];
var row_sums = [];
var all_sum = 0;
$table.find('tbody tr').each(function(row){
row_sums[row] = 0;
$(this).find('td input[type=text]').each(function(column){
value = parseInt(this.value);
row_sums[row] += value;
if (!col_sums[column]) col_sums[column] = 0;
col_sums[column] += value;
all_sum += value;
});
});
$.each(row_sums,function(index,value){
$table.find('tbody tr:eq('+index+') td:last').html(value);
});
$.each(col_sums,function(index,value){
$table.find('tfoot tr td:eq('+index+')').html(value);
});
$table.find('tfoot tr td:last').html(all_sum);
}
$(function(){
$('table.summonizer input[type=text]').live('change',function(){
summonize_table($(this).closest('table'));
});
$('table.summonizer input[type=text]:first').trigger('change');
});
您可以在此处查看一个有效的示例:http://jsfiddle.net/my9DF/