【问题标题】:jQuery Datatables Sum / Subtotal for Multiple Groups多个组的 jQuery 数据表总和/小计
【发布时间】:2017-02-24 01:30:44
【问题描述】:

我有一个包含 2 组行的数据表,我想获得一列的总和/小计,例如,每个分组行的年龄(我知道这没有意义;))。

这是JSFiddle

        $(document).ready(function() {
        var table = $('#example').DataTable({
    "ordering": false,
    "columnDefs": [
                { "visible": false, "targets": [2, 1] }
            ],
            "drawCallback": function(settings) {
                var api = this.api();
                    var rows = api.rows({ page: 'current' }).nodes();
                    var last = null;
                    var columns = [2,1];

                    for (c = 0; c < columns.length; c++) {
                        var colNo = columns[c];
                        api.column(colNo, { page: 'current' }).data().each(function (group, i) {
                            if (last !== group) {
                                $(rows).eq(i).before(
                                    '<tr class="group"><td colspan="4"><h4 style="font-weight: bold !important;">' + group + '</h4></td></tr>'
                                );
                                last = group;
                            }
                        });
                    }
            },
        });
    });

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:

    您可以在 .DataTable({}) 中添加"footerCallback" function

     "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( 3 )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
          // Total over this page
            pageTotal = api
                .column( 3, { page: 'current'} )
                .data()
                .reduce( function (a, b) {
                    return intVal(a) + intVal(b);
                }, 0 );
            // Update footer
            $( api.column( 3 ).footer() ).html(
                'Total age:'+pageTotal +' ( '+ total +' total)'
            );
          },
    

    我上传了你的jsfiddle

    你可以改变“column(3)”的数量来改变你想对哪一列求和。

    希望这会有所帮助:)

    【讨论】:

    • 谢谢你,但我需要实现的是为东京所有会计师(“东京>会计师”)的每个组 f.e.age 显示一个小计......
    • 在另一篇文章中从 Richard 那里找到了这个解决方案:stackoverflow.com/a/35657438/7019802 也许有人有想法在多个组中采用这个。
    猜你喜欢
    • 2014-09-16
    • 1970-01-01
    • 2011-10-14
    • 2021-11-23
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多