使用footer_callback对数据表页脚中的1+列求和? [英] sum on 1+ columns in datatables footer using footer_callback?
问题描述
鉴于此 footer_callback 数据表示例这是我的 FIDDLE.
Given this footer_callback datatables example here is my FIDDLE.
这基本上总结了 1 列的每列总数.谁能建议我如何为超过 1 列执行此操作?
This basically sums the total per column for 1 column. Can anyone advise how I can do this for more than 1 column?
我想我可能需要为要求和的列添加更多 th
标签:
I thought I might need to add more th
tags for the columns I want to sum:
<tfoot>
<tr>
<th colspan="4" style="text-align:right">Total:</th>
<th></th>
</tr>
</tfoot>
并为每一列添加另一个回调函数,但到目前为止我还没有感到高兴.谁能给点建议?
And add another callback function per each column, but so far I have had no joy. Can anyone advise?
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
// Remove the formatting to get integer data for summation
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;
};
// Total over all pages
total = api
.column( 4 )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Total over this page
pageTotal = api
.column( 4, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
// Update footer
$( api.column( 4 ).footer() ).html(
'$'+pageTotal +' ( $'+ total +' total)'
);
}
注意:我可能需要表/数据集中的另一列,其中包含我可以求和的数字.
更改了表格,因此有 2 列可以求和 FIDDLE.在这个小提琴中,它在第 5 列中工作,但如何让它在第 3 列中工作?
NOTE: I might need another column in the table/dataset with numbers that I can sum on.
Changed the table so there is 2 columns that can be summed FIDDLE.
In this fiddle it is working in col 5 but how do I get it to work in col 3?
推荐答案
查看 fiddle here一>.我正在使用 sum 插件.使用这种方法,您只需将列索引添加到数组中即可进行总计.
Check out the fiddle here. I'm using the sum plugin. With this approach, you can just add a column index to an array to total it.
我还添加了应用"过滤器,以便在过滤时动态更新总数.
I also added the 'applied' filter so the totals dynamically update when filtering.
$(document).ready(function() {
// SUM PLUGIN
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
if ( typeof a === 'string' ) {
a = a.replace(/[^d.-]/g, '') * 1;
}
if ( typeof b === 'string' ) {
b = b.replace(/[^d.-]/g, '') * 1;
}
return a + b;
}, 0 );
} );
$('#example').DataTable({
"footerCallback": function () {
var api = this.api(),
columns = [3, 5]; // Add columns here
for (var i = 0; i < columns.length; i++) {
$('tfoot th').eq(columns[i]).html('Total: ' + api.column(columns[i], {filter: 'applied'}).data().sum() + '<br>');
$('tfoot th').eq(columns[i]).append('Page: ' + api.column(columns[i], { filter: 'applied', page: 'current' }).data().sum());
}
}
});
});
这篇关于使用footer_callback对数据表页脚中的1+列求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!