【问题标题】:DataTables: total a column - except for rows with specific class?DataTables:总计一列-具有特定类的行除外?
【发布时间】:2015-09-04 12:30:07
【问题描述】:

我有总计一列的代码,但我有已经有总计的子组。除了灰色的总行之外,我可以合计列中的每个数字吗?

var table = $('#datatable');
var leng = table.find("tr:first").children().length;

    // add totals to new row
            for (var i = 0; i < leng; i++) {

                var total = api
                .column(i)
                .data()
                    .reduce(function (a, b) {
                        // return if it's not a value from the gray row
                        return intVal(a) + intVal(b);
                    });

                // correct any html mistakes that slip through
                if (isNaN(intVal(total)))
                    total = '';

                table.find("tfoot tr:first th").eq(i).html(total);
            };

【问题讨论】:

  • 也许灰色的行有一个特定的类?
  • 确实如此,但代码看起来如何?班级是'sgrouptotal'
  • 使用.not('.sgrouptotal') 排除所有类sgrouptotal

标签: javascript jquery datatables datatables-1.10


【解决方案1】:

为什么不在rows() API 方法上使用:not 选择器并根据剩余行计算总和?非常小的示例,将 col#1 的总和添加到回调中的页脚:

var table = $('#example').DataTable({
    drawCallback: function () {
        var api = this.api(),
            sum = 0;
        api.rows(":not('.sgrouptotal')").every(function() {
            sum += parseFloat(this.data()[0]);
        });    
        $(api.column(0).footer()).text(sum);
    }
});

演示 -> http://jsfiddle.net/j38bmagj/

以上内容应该很容易扩展到多列。在 sum4 += this.data()[4] 等同一循环中计算 col #4 的总和。

【讨论】:

    【解决方案2】:

    那么做呢?

    i = 0;          
    $('#datatable tr:first tr').each(function(key, value){
        if(!$(this).hasClass("sgrouptotal"){
            i += parseInt(value.text());
        }
    });
    

    【讨论】:

    • 这不起作用,因为 i 指的是列,其中有 4 - 而不是 12 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    • 2019-03-16
    • 2020-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多