jQuery 数据表 - 对单元格中包含 class 的列求和

jQuery Datatables - Sum Column with class in cell

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

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

有没有办法通过不仅声明列而且声明 class 来使用 footerCallback 方法?

或者让列求和的最佳方法是什么(并显示当前页面总和和所有页面的总和 - 这就是 footercallback 方法所发生的事情)

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

的选项

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

$(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)');
    }
});

});`

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

你的 reduce 方法有问题。

reduce 方法中的变量 b 不是数字(金钱),而是在看起来像

的列中使用的标签

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

步骤:

  1. 我首先通过b.replace('$', '')

  2. 去掉了开头的$
  3. 然后将字符串的其余部分转换为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

希望对您有所帮助。