单页多HTML表格合计计算实现方案(jQuery/JavaScript)
解决多表格合计计算的方案
针对你用Django循环生成多个表格,需要在每个表格的tfoot中计算「Total Amount」列合计的需求,这里提供一个基于jQuery的实现方案,步骤清晰且支持任意数量的表格:
第一步:调整Django模板的表格结构
首先要确保每个表格的tfoot有对应的列来放置合计值,同时给所有需要计算合计的表格添加一个通用类(比如summary-table),方便后续JS精准定位:
<div class="row"> <div class="table-responsive col-md-6"> <!-- 添加通用类 summary-table --> <table id="example" class="table table-striped table-bordered table-responsive-xl summary-table"> <caption style="caption-side:top; text-align: center;"><h3>Income</h3></caption> <thead class="thead-dark"> <tr> <th>Particulars</th> <th>Description</th> <th>Total Amount</th> </tr> </thead> <tbody> {% for item in all_profit %} {% if item.category.under == "Income" %} <tr> <td>{{item.category}}</td> <td>{{item.category.desc}}</td> <td>{{ item.balance }} </td> </tr> {% endif %} {% endfor %} </tbody> <tfoot> <tr class="totalColumn"> <td style="visibility:hidden;"></td> <td>Total:</td> <!-- 新增单元格用于显示合计 --> <td class="total-amount"></td> </tr> </tfoot> </table> </div> <!-- 第二个表格(比如Expense)也同样添加summary-table类和对应的tfoot结构 --> <div class="table-responsive col-md-6"> <table class="table table-striped table-bordered table-responsive-xl summary-table"> <!-- 其他结构类似,省略... --> </table> </div> </div>
第二步:编写jQuery/JavaScript计算逻辑
在模板的底部(或者单独的JS文件中)添加以下代码,它会自动遍历每个目标表格,计算对应列的合计并填充到tfoot中:
$(function() { // 遍历所有带summary-table类的表格 $('.summary-table').each(function() { const $currentTable = $(this); let totalAmount = 0; // 遍历当前表格tbody中每一行的第三列(Total Amount列,索引从0开始) $currentTable.find('tbody tr td:nth-child(3)').each(function() { // 提取文本并清理:去掉空格、货币符号等非数字内容 const rawAmount = $(this).text().trim().replace(/[^0-9.]/g, ''); // 确保是有效数字再累加 if (!isNaN(rawAmount) && rawAmount !== '') { totalAmount += parseFloat(rawAmount); } }); // 将合计值填充到当前表格的tfoot对应单元格,保留两位小数 $currentTable.find('tfoot .total-amount').text(totalAmount.toFixed(2)); }); });
关键细节说明
- 独立计算每个表格:通过
$('.summary-table').each()遍历每个表格,确保每个表格的合计是自己行的总和,不会和其他表格混淆。 - 数值清理处理:使用
replace(/[^0-9.]/g, '')去掉金额中的非数字字符(比如货币符号、空格),避免转换数字时出错。 - 边界情况处理:如果表格没有数据,合计会显示
0.00,符合预期;如果某行的金额无效(比如空值),会自动跳过,不影响合计。 - 列索引对应:
td:nth-child(3)对应第三列(Total Amount),如果你的表格列顺序调整,记得修改这个索引值。
内容的提问来源于stack exchange,提问作者Junior Developer
相关产品推荐
相关产品推荐

