17370845950

如何在动态过滤的透视表中正确计算可见单元格的行列总和

本文介绍如何修改 javascript 汇总逻辑,使 `counttotal()` 函数仅对 `display: none` 状态之外的 `

` 行和 `/ ` 单元格进行数值累加,从而确保员工/流程筛选后行列总计准确响应可见内容。

在实现可交互透视表(Pivot Table)时,常见的过滤策略是通过设置 display: none 隐藏不满足条件的行(如被禁用的员工)或列(如被取消勾选的流程)。然而,原始的 countTota

l() 函数未考虑元素的可见性状态,导致隐藏行/列仍参与求和计算,最终总和失真。

核心问题在于:

  • 列汇总(按员工):需跳过 display: none 的 或 单元格;
  • 行汇总(按流程):需跳过整行被隐藏(即 )所对应的单元格,而非仅判断单元格自身——因为列过滤作用于 / ,而行过滤作用于 。

    ✅ 正确解决方案如下:

    1. 列方向求和(每位员工的各流程工时总和)
      对每个员工类名(如 john-doe)匹配的所有 元素,检查其自身 style.display 是否为 'none' —— 因为列过滤直接作用于单元格:
      cells.forEach(cell => {
        const textContent = parseFloat(cell.textContent.trim()) || 0;
        if (cell.style.display !== 'none') { // ✅ 关键判断:仅统计可见单元格
          colSum += textContent;
        }
      });
      1. 行方向求和(每项流程下所有可见员工工时总和)
        对每个流程类名(如 design)匹配的所有 元素,应检查其父 的显示状态,因为员工/活跃状态过滤是通过隐藏整行实现的:
        cells.forEach(cell => {
          const textContent = parseFloat(cell.textContent.trim()) || 0;
          if (cell.parentNode.style.display !== 'none') { // ✅ 关键判断:仅当所在行可见才计入
            rowSum += textContent;
          }
        });

        ⚠️ 注意事项:

        • cell.style.display 仅反映内联样式(element.style.display),若隐藏是通过 CSS 类(如 .hidden { display: none; })控制,则需改用 getComputedStyle(cell).display === 'none';
        • 但根据您提供的过滤逻辑(row.style.display = 'none' 和 cell.style.display = 'none'),直接使用 style.display 是安全且高效的;
        • 建议将 parseFloat(...) 的容错逻辑统一为 Number(cell.textContent.trim()) || 0,更简洁且语义清晰;
        • .round(2) 并非原生 JavaScript 方法,请确保已正确定义(例如 Number.prototype.round = function(p) { return +this.toFixed(p); };),或改用 Math.round(value * 100) / 100。

        ? 最终优化版函数(含健壮性增强):

        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,即可实现“所见即所算”的精准动态汇总。