使用footer_callback在datatables页脚中的1+列上求和? [英] sum on 1+ columns in datatables footer using footer_callback?
问题描述
鉴于此 footer_callback 数据表示例
这里是我的 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)'
);
}
注意:我可能需要另一列表/数据集,我可以总结的数字。
更改了表格,因此有两列可以相加: FIDDLE 。
在这个小提琴中,它正在col 5中工作,但是如何让它在col 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?
推荐答案
查看这里的小提琴。我正在使用 sum plugin 。使用这种方法,您可以添加一个列索引到数组来完成它。
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.
我还添加了应用过滤器,以便过滤时总计动态更新。 / p>
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在datatables页脚中的1+列上求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!