列的SUM总计

请参考上一个问题: jQuery中列的总和

我使用了Aymen的解决方案,但我编辑它以满足我的需求。 它停止工作,我的代码如下jsfiddle所见: http : //jsfiddle.net/unKDk/15/

Apple Orange Watermelon Strawberry Total By Row
1 2 3 4
1 2 3 4
1 5 3 4
Total: Total: Total: Total: Total:

Jquery部分是

 var totals=[0,0,0,0,0]; $(document).ready(function(){ var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')"); $dataRows.each(function() { $(this).find('.rowAA').each(function(i){ totals[i]+=parseInt( $(this).html()); }); $(this).find('.rowBB').each(function(i){ totals[i]+=parseInt( $(this).html()); }); }); $("#sum_table td.totalCol").each(function(i){ $(this).html("total:"+totals[i]); }); }); 
  1. 如何解决导致jquery错误计算的问题。
  2. 如何按行计算总数
  3. 我需要类名完全相同。

我不太确定你想要什么,但是如果你只是想按列加总所有行,那么请看下面..

 var totalsByRow = [0, 0, 0, 0, 0]; var totalsByCol = [0, 0, 0, 0, 0]; $(document).ready(function() { var $dataRows = $("#sum_table tr:not('.totalColumn, .titlerow')"); $dataRows.each(function(i) { $(this).find('td:not(.totalRow)').each(function(j) { totalsByCol[j] += parseInt($(this).html()); totalsByRow[i] += parseInt($(this).html()); }); }); for (var i = 0; i < totalsByCol.length - 1; i++) { totalsByCol[totalsByCol.length - 1] += totalsByCol[i]; } $("#sum_table td.totalCol").each(function(i) { $(this).html("total:" + totalsByCol[i]); }); $("#sum_table td.totalRow").each(function(i) { $(this).html("total:" + totalsByRow[i]); }); }); 

DEMO

基本上,您希望定位中间行中的所有td元素。 每次循环一个新的td ,您希望将其值添加到其行中的最后一个td(除非它是该行中的最后一个td ),并且还要添加到共享其索引的最后一行中的td

 $("#sum_table tr:not(:first,:last)").each(function(c,row) { $("td",row).text(function(i,t) { var n = parseInt( t, 10 ) || 0; $(this).nextAll(":last-child").text(function(a,o) { return n + ( parseInt( o, 10 ) || 0 ); }); $(row).nextAll("tr:last").find("td:nth-child("+(++i)+")").text(function(a,o){ return "Total: " + ( n + ( parseInt( o.replace(/[^\d]/g,""), 10 ) || 0 ) ); }); }); }); 

这适用于任何大小的表,不限制您使用x列或y行。

小提琴: http : //jsfiddle.net/unKDk/34/

评论

我建议您阅读下面示例中的注释,因为它们将帮助您了解每行的内容。

 // For each table row that is not first or last $("#sum_table tr:not(:first,:last)").each(function(c,row) { // For each td within this row $("td",row).text(function(i,t) { // Determine numerical value of this td's content var n = parseInt( t, 10 ) || 0; // Find last td in this row, change its text $(this).nextAll(":last-child").text(function(a,o) { // Increment its value with the value of current TD return n + ( parseInt( o, 10 ) || 0 ); }); // Find last row, and td within of same index as current td, change its text $(row).nextAll("tr:last").find("td:nth-child("+(++i)+")").text(function(a,o){ // Increment its value (removing non-numbers) with the value of current td return "Total: " + ( n + ( parseInt( o.replace(/[^\d]/g,""), 10 ) || 0 ) ); }); // End our td loop }); // End our tr loop });