本文介绍如何修改 javascript 汇总逻辑,使 `counttotal()` 函数仅对 `display: none` 状态之外的 `
在实现可交互透视表(Pivot Table)时,常见的过滤策略是通过设置 display: none 隐藏不满足条件的行(如被禁用的员工)或列(如被取消勾选的流程)。然而,原始的 countTota

核心问题在于:
✅ 正确解决方案如下:
cells.forEach(cell => {
const textContent = parseFloat(cell.textContent.trim()) || 0;
if (cell.style.display !== 'none') { // ✅ 关键判断:仅统计可见单元格
colSum += textContent;
}
});cells.forEach(cell => {
const textContent = parseFloat(cell.textContent.trim()) || 0;
if (cell.parentNode.style.display !== 'none') { // ✅ 关键判断:仅当所在行可见才计入
rowSum += textContent;
}
});⚠️ 注意事项:
? 最终优化版函数(含健壮性增强):
function countTotal() {
const tables = Array.from(document.querySelectorAll('tbody'));
tables.forEach(table => {
// === 列汇总:每位员工的总工时(排除 display:none 的单元格)===
const trs = Array.from(table.querySelectorAll('tr')).slice(1, -1); // 排除首行(标题)和末行(总计)
const employees = [...new Set(trs.map(tr => {
const firstDataCell = tr.cells[1]; // 假设员工名在第2列(索引1)
return firstDataCell ? firstDataCell.classList[0] : null;
}).filter(Boolean))];
employees.forEach(employee => {
let colSum = 0;
const cells = table.querySelectorAll(`td.${employee}, th.${employee}`);
cells.forEach(cell => {
if (cell.style.display !== 'none') {
const val = Number(cell.textContent.trim());
colSum += isNaN(val) ? 0 : val;
}
});
const totalCell = table.querySelector(`td.${employee}.total-row`);
if (totalCell) totalCell.textContent = colSum.toFixed(2);
});
// === 行汇总:每项流程的总工时(排除 display:none 的行)===
const headerRow = table.querySelector('tr:first-child');
const processHeaders = headerRow.querySelectorAll('th:not(:first-child):not(:last-child)');
const processes = Array.from(processHeaders)
.map(th => th.classList[0])
.filter(cls => cls && cls !== 'total-row');
processes.forEach(process => {
let rowSum = 0;
const cells = table.querySelectorAll(`td.${process}`);
cells.forEach(cell => {
if (cell.parentNode.style.display !== 'none') { // ✅ 检查父行是否可见
const val = Number(cell.textContent.trim());
rowSum += isNaN(val) ? 0 : val;
}
});
const totalCell = table.querySelector(`td.${process}.total-col`);
if (totalCell) totalCell.textContent = rowSum.toFixed(2);
});
});
}该方案完全适配您当前的 DOM 结构与过滤机制,无需重构 HTML 或 CSS,即可实现“所见即所算”的精准动态汇总。