【问题标题】:how to add multiple column sum total in datatable如何在数据表中添加多列总和
【发布时间】:2016-04-25 13:55:30
【问题描述】:

我在显示数据表中某些列的总和时遇到问题。一个问题是我的表是动态创建的,即用户选择要显示的列,因此列索引不固定!

其次,添加代码时的 footerCallback 抛出 ncaught TypeError: Cannot read property 'nTf' of undefined error

<tfoot>
  <tr>
    <td colspan='2'> <span style="float:right;"id ='totalcol1'></span> </td>
  </tr>
</tfoot>

FooterCAllback 在 var table=('#mytable').Datatable() 中定义

 "footerCallback": function ( row, data, start, end, display ) {
  var api = this.api(), data;
  $(api.column(11).footer()).html(
        api.column(11).data().reduce( function ( a, b ) { return a + b;})
     );
/* For second column
  $(api.column(12).footer()).append(
        api.column(12).data().reduce( function ( a, b ) { return a + b;})
     );*/
 },

【问题讨论】:

    标签: datatable datatables


    【解决方案1】:

    我找到了一个example,看起来正是你想要做的

    $(document).ready(function() {
        $('#example').DataTable( {
            "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)'
                );
            }
        } );
    } );
    

    【讨论】:

    • 谢谢我已经尝试过了,我的问题是列索引是动态的..我不能像上面显示的那样使用 4,如果某些字段(工资,税)只存在,那么总行页脚需要插入动态结果中。
    • 关于索引,您可以使用变量而不是“4”。因此,当您更改列索引时,代码将适合更改(只要您更新变量值)
    • 如果没有显示列(工资、税),您也可以自己隐藏页脚
    • 谢谢拉斐尔,我正在努力
    猜你喜欢
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-06
    相关资源
    最近更新 更多