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

基于JSON数据生成表格后,统计count与pipelinevalue总和并添加总计行

解决方案:添加总计行到表格页脚并计算总和

我帮你修改了代码,解决了统计总和并添加总计行到表格页脚的需求,同时修正了原代码里的拼写错误和标签问题:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="geo_summary">
  <thead style="background-color: #00f; color: #fff">
    <tr>
      <th style="background-color: #66cdf2; color: #000">Opportunity</th>
      <th style="background-color: #66cdf2; color: #000">Pipeline Count</th>
      <th style="background-color: #66cdf2; color: #000">Pipeline Value</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
  <tfoot></tfoot> <!-- 修正了标签拼写错误:tfooter → tfoot -->
</table>

<script>
const pipeline = [
  {Geo: "APAC", SalesStage: "Proposal Submitted", count: 11, pipelinevalue: 1}, 
  {Geo: "NSU", SalesStage: "Proposal Submitted", count: 4, pipelinevalue: 2}, 
  {Geo: "Middle East", SalesStage: "Proposal Submitted", count: 17, pipelinevalue: 1}, 
  {Geo: "US East", SalesStage: "Proposal Submitted", count: 14, pipelinevalue: 1}, 
  {Geo: "Europe", SalesStage: "Proposal Submitted", count: 9, pipelinevalue: 2}, 
  {Geo: "US West", SalesStage: "Proposal Submitted", count: 6, pipelinevalue: 1}
]; 

// 修正了函数名拼写:genetateTable → generateTable
generateTable(pipeline,'#geo_summary thead','#geo_summary tbody',pipeval='1'); 

function generateTable(pipeline, divHeader, divBody, pipeval) { 
  // 初始化总和变量
  let totalCount = 0;
  let totalPipelineValue = 0;

  $.each(pipeline, function (index, item) { 
    const $tr = $('<tr>'); 
    // 累加当前项的count和pipelinevalue
    totalCount += item.count;
    totalPipelineValue += item.pipelinevalue;

    if(pipeval === '1'){ 
      $tr.append([item.SalesStage, item.count, item.pipelinevalue].map(x => $('<td>').text(x))); 
    } else {
      $tr.append([item.SalesStage, item.count].map(x => $('<td>').text(x)));
    }
    $(divBody).append($tr); 
  }); 

  // 生成总计行并添加到tfoot
  const $totalTr = $('<tr>');
  $totalTr.append('<td>Total</td>');
  $totalTr.append(`<td>${totalCount}</td>`);
  if(pipeval === '1'){
    $totalTr.append(`<td>${totalPipelineValue}</td>`);
  }
  $('#geo_summary tfoot').append($totalTr);
} 
</script>

关键修改说明:

  1. 标签修正:把原代码里错误的<tfooter>标签改成了标准的<tfoot>(HTML表格页脚的正确标签是tfoot)
  2. 函数名修正:修正了genetateTable的拼写错误为generateTable,避免运行报错
  3. 总和计算:在遍历数据时,同步累加count和pipelinevalue的总和到totalCount和totalPipelineValue变量中
  4. 总计行生成:遍历完成后,根据pipeval参数生成对应列数的总计行,并插入到表格的<tfoot>中,确保总计行显示在表格底部
  5. 代码健壮性:把字符串比较从==改成了===,遵循严格相等的最佳实践

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:37:27