JS 实现表格数据汇总(适用于任何页面)

在文章或页面中添加以下脚本,实现自动汇总“金额”列(第2列)并在表格底部追加一行:

<script>
document.addEventListener("DOMContentLoaded", function () {
  const table = document.querySelector(".wp-block-table table");
  if (!table) return;

  let sum = 0;
  const rows = table.querySelectorAll("tbody tr");

  rows.forEach(row => {
    const amountCell = row.children[1];
    const amountText = amountCell.textContent.trim();
    const amount = parseFloat(amountText);
    if (!isNaN(amount)) {
      sum += amount;
    }
  });

  // 创建汇总行
  const totalRow = document.createElement("tr");
  totalRow.innerHTML = `
    <td><strong>合计</strong></td>
    <td><strong>${sum.toFixed(2)}</strong></td>
    <td colspan="2"></td>
  `;
  table.querySelector("tbody").appendChild(totalRow);
});
</script>

🔧 使用方式:

  1. 在文章中插入一个“自定义 HTML”模块,或在主题页脚加这个脚本。
  2. 确保表格使用 class="wp-block-table",或自行修改脚本中的选择器。
© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容