<table id="sum_table" width="300" border="1"> <tr class="titlerow"> <td>Apple</td> <td>Orange</td> <td>Watermelon</td> <td>Strawberry</td> <td>Total By Row</td> </tr> <tr> <td class="rowAA">1</td> <td class="rowAA">2</td> <td class="rowBB">3</td> <td class="rowBB">4</td> <td class="totalRow"></td> </tr> <tr> <td class="rowAA">1</td> <td class="rowAA">2</td> <td class="rowBB">3</td> <td class="rowBB">4</td> <td class="totalRow"></td> </tr> <tr> <td class="rowAA">1</td> <td class="rowAA">5</td> <td class="rowBB">3</td> <td class="rowBB">4</td> <td class="totalRow"></td> </tr> <tr class="totalColumn"> <td class="totalCol">Total:</td> <td class="totalCol">Total:</td> <td class="totalCol">Total:</td> <td class="totalCol">Total:</td> <td class="totalCol">Total:</td> </tr> </table>
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]); }); });
我不太确定自己想要什么,但是如果您只想按列汇总所有行,请参见下文。
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]); }); });
演示