You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML表格中计算Fees-1列所有行数值总和并在底部行显示‘Total’?

如何在表格底部添加Total行并计算指定列的总和

嘿,这个需求太常见了!针对你用JSTL渲染的表格,我给你两种实用的解决方案,你可以根据自己的场景来选:

方案一:后端提前计算总和(推荐,更高效)

既然你的表格数据是从后端通过${FEE_LIST}传过来的,那最好在后端Java代码里就把Fees-1的总和算好,这样不用前端再遍历计算,性能更好,也避免前端可能出现的格式问题。

后端代码示例(Java)

假设你在后端的Controller里处理数据:

List<FeesReport> feeList = // 从数据库或其他数据源获取数据
double sumFees1 = 0.0;
for (FeesReport report : feeList) {
    // 处理null值,避免空指针异常
    if (report.getFees1() != null) {
        sumFees1 += report.getFees1();
    }
}
// 将总和与数据列表一起传入JSP
request.setAttribute("sumFees1", sumFees1);
request.setAttribute("FEE_LIST", feeList);

JSP表格修改

在</c:forEach>循环结束后,直接添加Total行:

<table id="tableID">
 <thead>
 <tr>
 <th>ID</th>
 <th>Fees-1</th>
 <th>Fees-2</th>
 </tr>
 </thead>
 <tbody>
 <c:forEach var="feesReport" items="${FEE_LIST}">
 <tr>
 <td>${feesReport.id}</td>
 <td>${feesReport.fees1}</td>
 <td>${feesReport.fees2}</td>
 </tr>
 </c:forEach>
 <!-- 新增的Total行 -->
 <tr style="font-weight: bold;">
 <td>Total</td>
 <td>${sumFees1}</td>
 <td></td> <!-- 如果需要Fees-2的总和,后端同理计算后传入即可 -->
 </tr>
 </tbody>
</table>

页面加载时直接显示总和,稳定性拉满。

方案二:前端JavaScript动态计算(适合不想改后端的场景)

如果暂时不想调整后端逻辑,也可以用JavaScript在页面加载完成后,遍历表格行计算总和,再动态插入Total行。

完整JS代码

把这段代码放在</body>标签前,或者用DOM加载完成事件触发:

document.addEventListener('DOMContentLoaded', function() {
    const table = document.getElementById('tableID');
    const tbody = table.querySelector('tbody');
    let totalFees1 = 0.0;

    // 遍历tbody内的所有数据行
    const rows = tbody.querySelectorAll('tr');
    rows.forEach(row => {
        // 获取第二列(Fees-1,索引从0开始)的内容
        const fees1Cell = row.querySelector('td:nth-child(2)');
        if (fees1Cell) {
            const fees1Value = parseFloat(fees1Cell.textContent.trim());
            // 确保是有效数字再累加
            if (!isNaN(fees1Value)) {
                totalFees1 += fees1Value;
            }
        }
    });

    // 创建Total行元素
    const totalRow = document.createElement('tr');
    totalRow.style.fontWeight = 'bold';

    // 创建单元格并填充内容
    const totalLabelCell = document.createElement('td');
    totalLabelCell.textContent = 'Total';
    const totalValueCell = document.createElement('td');
    totalValueCell.textContent = totalFees1.toFixed(2); // 保留两位小数,可按需调整
    const emptyCell = document.createElement('td');

    // 组装行并添加到表格底部
    totalRow.appendChild(totalLabelCell);
    totalRow.appendChild(totalValueCell);
    totalRow.appendChild(emptyCell);
    tbody.appendChild(totalRow);
});

注意:如果表格数据是异步加载的,需要在数据渲染完成后再执行这段代码哦。

内容的提问来源于stack exchange,提问作者stack321

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 09:42:45