如何添加数据表自定义行呈现/聚合



我试图添加自定义行到服务器端呈现的数据表,以显示列的总量下面是表头是怎样的日期|名称|金额| Ref |

<table id="tableExport_filter">
<thead>
<tr>
<th>Date</th>
<th>Name</th>
<th>Amount</th>
<th>Ref</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>                                   
</table>

使用AJAX

获取数据
var dataTable = $('#tableExport_filter').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'ajax': {
'url':'app/functions/collections_by_agent.php',
'data': function(data){}
},
'columns': [

{ data: 'date_created'},
{ data: 'name'},
{ data: 'amount' }, 
{ data: 'ref' }
],
});

我需要帮助添加添加amount列的Sum total

我建议使用表脚<tfoot>,而不是在表体中添加新行。

步骤:

  1. 在HTML表中,在结束<tbody>标记后添加一个空页脚:
<tfoot>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tfoot>
  1. 为DataTable添加footerCallback选项:
var dataTable = $('#tableExport_filter').DataTable({
// your existing options go here
"footerCallback": function( tfoot, data, start, end, display ) {
var api = this.api();
$( api.column( 2 ).footer() ).html(
api.column( 2 ).data().reduce( function ( a, b ) {
return a + b;
}, 0 )
);
}
} );

在这个函数中,您使用var api = this.api();从表本身内部获得对DataTables API函数的访问。

然后选择页脚的列索引2(即第3列)作为sum的目标。

最后,使用reduce函数对数据列索引2中的所有值求和。函数末尾的0是执行reduce函数初始步骤时使用的起始值。

这里记录了页脚回调。

reduce函数的文档在这里。

最新更新