Javascript DataTables.net 表列总和在页脚中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27918051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:53:33  来源:igfitidea点击:

DataTables.net table column sum in footer

javascriptjquerydatatablesjquery-datatables

提问by skepnaden

I'm having issues with a tiny detail in inserting the sum value of each column, with class "sum", into its footer.

我在将每列的总和值(类别为“sum”)插入其页脚时遇到了一个小细节问题。

The code (more or less taken straight from DataTables.net) goes:

代码(或多或少直接取自 DataTables.net)如下:

var table = $('#example').DataTable();
        table.columns('.sum').each(function (el) {
            var sum = table
                .column(el)
                .data()
                .reduce(function (a, b) {
                    return parseInt(a, 10) + parseInt(b, 10);
                });
            $(el).html('Sum: ' + sum);
        });

"sum" has the correct value but is somehow not inserted into the footer! I.e. its -element shows up empty.

“sum”具有正确的值,但不知何故未插入页脚!即它的 -element 显示为空。

Note that the snippet below works fine, but I want to sum each column with class sum.

请注意,下面的代码段工作正常,但我想用类 sum 对每一列求和。

var table = $('#example').DataTable();
var column = table.column(4);

$(column.footer()).html(
    column.data().reduce(function (a, b) {
        return parseInt(a, 10) + parseInt(b, 10);
    })
);

////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////// ///////////////////////////////////

EDIT - Workaround:

编辑 - 解决方法:

I moved the code to where the DataTable is initialized and went with footerCallback instead. See below code:

我将代码移到初始化 DataTable 的位置,并改为使用 footerCallback。见下面的代码:

"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 this page
                    pageTotal = api
                        .column('.sum', { page: 'current' })
                        .data()
                        .reduce(function (a, b) {
                            return intVal(a) + intVal(b);
                        }, 0);

                    // Update footer
                    $(api.column('.sum').footer()).html(pageTotal);
                }

Somehow now the value is inserted into the right tfoot element. Still no idea why it wouldn't work in the first place (but as mentioned in comment order of including JS-files could have had to do with some of it).

现在以某种方式将该值插入到正确的 tfoot 元素中。仍然不知道为什么它首先不起作用(但正如评论顺序中提到的,包括 JS 文件可能与其中的一些有关)。

Now I just have to figure out how to loop multiple columns with class="sum"...

现在我只需要弄清楚如何使用 class="sum" 循环多个列...

采纳答案by Gyrocode.com

Your table manipulation code needs to be executed only when DataTable is initialized, (see initCompleteproperty).

只有在初始化 DataTable 时才需要执行表操作代码(请参阅initComplete属性)。

Also make sure you have <tfoot></tfoot>block defined in your <table>otherwise there would be no footer.

还要确保您<tfoot></tfoot>在您的块中定义了块,<table>否则将没有页脚。

Otherwise you were very close to the solution, please see below the corrected code:

否则,您非常接近解决方案,请参阅下面更正后的代码:

var table = $('#ticketTable').DataTable({
    'initComplete': function (settings, json){
        this.api().columns('.sum').every(function(){
            var column = this;

            var sum = column
                .data()
                .reduce(function (a, b) { 
                   a = parseInt(a, 10);
                   if(isNaN(a)){ a = 0; }                   

                   b = parseInt(b, 10);
                   if(isNaN(b)){ b = 0; }

                   return a + b;
                });

            $(column.footer()).html('Sum: ' + sum);
        });
    }
});

See this JSFiddlefor an example.

有关示例,请参阅此 JSFiddle

UPDATE

更新

There is also footerCallbackproperty that lets you defined footer display callback function which will be called on every "draw" event.

还有footerCallback属性可以让您定义页脚显示回调函数,该函数将在每个“绘制”事件上调用。

The difference between initCompleteand footerCallbackis that initCompleteis called once and footerCallbackon every "draw" event.

initComplete和之间的区别footerCallback是在每个“绘制”事件上initComplete调用一次footerCallback

If you're displaying the sum for the whole table, initCompleteshould suffice. Otherwise if you require to show in the footer data relevant for current page only (as in Footer callback example), use footerCallbackinstead.

如果您要显示整个表的总和,initComplete应该足够了。否则,如果您只需要在与当前页面相关的页脚数据中显示(如页脚回调示例),请footerCallback改用。

回答by Viktor Bogutskii

Mix. Empty replaced to 0

混合。空替换为0

"initComplete": function (settings, json) {
        this.api().columns('.sum').every(function () {
            var column = this;

            var intVal = function (i) {
                return typeof i === 'string' ?
                i.replace(/[$,]/g, '') * 1 :
                    typeof i === 'number' ?
                        i : 0;
            };

            var sum = column
                .data()
                .reduce(function (a, b) {
                    return intVal(a) + intVal(b);
                });

            $(column.footer()).html('Sum: ' + sum);
        });
    }