下面直接给你最实用、最常见的列运算(calculated column + 底部合计统计)方法,jQuery EasyUI datagrid 支持超级好,复制粘贴就能用,领导最爱的“单价*数量=金额自动计算 + 底部总金额/平均值”全都有!
方法1:行内计算列(比如金额 = 单价 × 数量,编辑时自动计算)
结合行内编辑,超级实用!
<tableid="dg"class="easyui-datagrid"title="列运算 + 底部合计"style="width:800px;height:400px"data-options="url:'data.json', singleSelect:true, fitColumns:true, pagination:true, showFooter:true, onClickRow:onClickRow, onEndEdit:onEndEdit"><thead><tr><thdata-options="field:'id',width:60">ID</th><thdata-options="field:'name',width:120">商品名称</th><thdata-options="field:'price',width:100,align:'right',editor:{type:'numberbox',options:{precision:2}}">单价</th><thdata-options="field:'quantity',width:100,align:'right',editor:{type:'numberbox',options:{precision:0,min:1}}">数量</th><thdata-options="field:'amount',width:120,align:'right', formatter:function(value,row){return (row.price*row.quantity).toFixed(2);}">金额(自动计算)</th></tr></thead></table><script>// 行内编辑核心(和之前一样)vareditIndex=undefined;functionendEditing(){if(editIndex==undefined){returntrue}if($('#dg').datagrid('validateRow',editIndex)){$('#dg').datagrid('endEdit',editIndex);editIndex=undefined;returntrue;}else{returnfalse;}}functiononClickRow(index){if(editIndex!=index){if(endEditing()){$('#dg').datagrid('selectRow',index).datagrid('beginEdit',index);editIndex=index;}else{$('#dg').datagrid('selectRow',editIndex);}}}// 编辑结束时自动计算金额functiononEndEdit(index,row,changes){if(changes.price||changes.quantity){row.amount=(row.price||0)*(row.quantity||1);$('#dg').datagrid('refreshRow',index);// 可选:更新底部合计updateFooter();}}// 加载成功后计算底部合计functionupdateFooter(){varrows=$('#dg').datagrid('getRows');vartotalAmount=0;vartotalQuantity=0;$.each(rows,function(i,row){totalAmount+=(row.price||0)*(row.quantity||1);totalQuantity+=(row.quantity||1);});varavgPrice=totalQuantity?(totalAmount/totalQuantity).toFixed(2):0;$('#dg').datagrid('reloadFooter',[{name:'<b>合计</b>',price:'',quantity:totalQuantity,amount:totalAmount.toFixed(2)+' (平均单价: '+avgPrice+')'}]);}$(function(){$('#dg').datagrid({onLoadSuccess:function(){updateFooter();}});});</script>效果:编辑单价或数量时,金额列自动计算并刷新;底部固定显示“合计”行,总金额 + 平均单价,超级专业!
方法2:纯客户端动态追加“合计”行(不依赖后台footer)
适合本地数据或不想改后台的情况。
functioncompute(columnField){varrows=$('#dg').datagrid('getRows');vartotal=0;for(vari=0;i<rows.length;i++){total+=parseFloat(rows[i][columnField]||0);}returntotal.toFixed(2);}$('#dg').datagrid({onLoadSuccess:function(){$(this).datagrid('appendRow',{name:'<span style="font-weight:bold;">合计</span>',amount:'<span style="font-weight:bold;">'+compute('amount')+'</span>'});}});方法3:后台直接返回footer(最省事,如果能改后台)
后台JSON格式:
{"total":20,"rows":[/* 数据行 */],"footer":[{"name":"合计","amount":99999.99}]}前端只需加showFooter:true,自动显示底部合计!
你现在直接复制方法1到你的页面,刷新就能看到列运算 + 底部合计效果了!
结合之前的复选框 + 分页 + 行内编辑 + 扩展编辑器,完美财务/订单报表就齐活了。
想要我给你一个完整的HTML示例(带远程数据 + 多列运算 + 总计/平均/最大值 + 保存到服务器)?
或者你告诉我你想计算什么(比如“成本 = 单价数量折扣”、“选中行合计”),我2分钟发你完整代码,复制就能跑!
快说说你现在的需求(比如“要分组统计”或“分页时每页合计”),我手把手帮你搞定,5分钟内看到完美列运算效果!