【问题标题】:jQuery Datatables - Sum Column with class in celljQuery Datatables - 单元格中带有类的求和列
【发布时间】:2015-03-17 23:43:41
【问题描述】:

我正在尝试对 datatables.net 表(第 5、6、7 列)中的几列求和,以便在每列的页脚中显示该列的总和。

问题是一个单元格中有多个值,而其他单元格的值包含在 span 标签中。因此总数显示为 NaN

有没有办法使用footerCallback 方法,不仅要声明列,还要声明类?

或者什么是获得列总和的最佳方法(并显示当前页面总和以及所有页面的总和 - 这是使用 footercallback 方法发生的情况)

我尝试了许多不同的方法,包括声明变量、添加 .cell ('.classname') 和 .cells (.'classname') 但没有返回总和。如果单元格中除了值之外没有其他任何东西,它似乎可以正常工作,但这不是我的表格的选项。

这是我正在使用的数据表代码:

$(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(6)
            .data()
            .reduce(function (a, b) {
            return intVal(a) + intVal(b);
        });

        // Total over this page
        pageTotal = api.column(6, {
            page: 'current'
        })
            .data()
            .reduce(function (a, b) {
            return intVal(a) + intVal(b);
        }, 0);

        // Update footer
        $(api.column(6).footer()).html(
            '$' + pageTotal + ' ( $' + total + ' total)');
    }
});

});`

表格代码相当复杂,所以我创建了一个 jsfiddle:http://jsfiddle.net/Ittavi/9p7tkqsn/

【问题讨论】:

    标签: jquery class sum datatables cell


    【解决方案1】:

    你的 reduce 方法有问题。

    reduce 方法中的变量 b 不是数字(金钱),而是列中使用的标签,看起来像

    $<span class=" addExpChangedClass amtField paymentparent1 sumamount" data-sort="1.00">1.00</span>

    步骤:

    1. 我最开始把$去掉了b.replace('$', '')

    2. 然后将字符串的其余部分转换为 jQuery 对象,以便可以提取值(即金额)$(b.replace('$', '')).text();

    最后如下图

    total = api.column(6)
      .data()
      .reduce(function(total, b) {
        b = $(b.replace('$', '')).text();
        return total + parseInt(b);
      }, 0);
    // Total over this page
    pageTotal = api.column(6, {
        page: 'current'
      })
      .data()
      .reduce(function(total, b) {
        b = $(b.replace('$', '')).text();
        return total + parseInt(b);
      }, 0);
    

    这是更新后的demo

    希望这会有所帮助。

    【讨论】:

    • 完美运行!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 2012-01-31
    • 2016-06-16
    • 1970-01-01
    • 2012-11-18
    相关资源
    最近更新 更多