在不使用 HTML 的情况下通过 Javascript 添加 jquery 数据表表页脚

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30275932/
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 04:54:28  来源:igfitidea点击:

Add jquery datatables table footer via Javascript without using HTML

javascriptjquerydatatables

提问by Ingo Fischer

I define my jquery datatables without any HTML besides the base table element. This is my HTML:

除了基表元素之外,我定义了没有任何 HTML 的 jquery 数据表。这是我的 HTML:

<table id="mytable"></table>

Then I do all the table configuration via the datatables definition. Example code:

然后我通过数据表定义完成所有表配置。示例代码:

var dataSet = [
    {name: "storage101", size: 492},
    {name: "storage102", size: 742},
    {name: "storage103", size: 423}
]

$.extend($.fn.dataTable.defaults, {
    sDom: '<"top"i>rCt<"bottom"flp><"clear">'
});

$("#storages").dataTable({
    data: dataSet,
    aoColumns: [
        {title: "Name", mData: "name"},
        {title: "Size", mData: "size"}
    ],
    oLanguage: {sEmptyTable: "No logs"},
    fnFooterCallback: function(nRow, aaData, iStart, iEnd, aiDisplay) {
        var api = this.api();
        var size = 0;
        aaData.forEach(function(x) {
            size += (x['size']);
        });
        // I need a footer in my table before doing this, what is the smartest way to add the footer?
        $(api.column(1).footer()).html(
            size
        );        
    }
});

Now I would like to use the footer callback to show sums of my dataset inside the footer.

现在我想使用页脚回调在页脚中显示我的数据集的总和。

Unfortunately, adding HTML to the footer (like in this example: https://datatables.net/examples/advanced_init/footer_callback.html) does not work as the table does not contain any tfoot element and the required row and columns. What would be a clean way to add footer for all my columns?

不幸的是,将 HTML 添加到页脚(如本例中:https: //datatables.net/examples/advanced_init/footer_callback.html)不起作用,因为该表不包含任何 tfoot 元素以及所需的行和列。为我的所有列添加页脚的干净方法是什么?

JSFiddle with the code above: http://jsfiddle.net/36twp251/1/

JSFiddle与上面的代码:http: //jsfiddle.net/36twp251/1/

采纳答案by Ingo Fischer

As the other answers say I need to define the footer beforehands somehow. Not perfect, but at least I can keep my HTML clean (just defining table and its id but nothing more):

正如其他答案所说,我需要以某种方式事先定义页脚。不完美,但至少我可以保持我的 HTML 干净(只定义表及其 id,仅此而已):

// globally defined table to be reused in several views
$.fn.storageTable = function() {
    $(this).append("<tfoot><tr><td></td><td></td></tr></tfoot>")
    return this.dataTable({
        data: dataSet,
        aoColumns: [
            {title: "Name", mData: "name"},
            {title: "Size", mData: "size"}
        ],
        oLanguage: {sEmptyTable: "No logs"},
        fnFooterCallback: function(nRow, aaData, iStart, iEnd, aiDisplay) {
            var api = this.api();
            var size = 0;
            aaData.forEach(function(x) {
                size += (x['size']);
            });
            $(api.column(1).footer()).html(size);       
        }
    });
}

// sample usage
$("table-storages").storageTable();

JSFiddle: http://jsfiddle.net/ifischer/Ljwgrkq0/3/

JSFiddle:http: //jsfiddle.net/ifischer/Ljwgrkq0/3/

回答by Gyrocode.com

CAUSE

原因

It's not possible to manipulate footer without presence of <tfoot>element.

在没有<tfoot>元素的情况下无法操作页脚。

SOLUTION #1

解决方案#1

Add appropriate markup as described in DataTables - Installation.

添加适当的标记,如数据表 - 安装中所述

SOLUTION #2

解决方案#2

If you don't have access to HTML, see alternative solutions below.

如果您无权访问 HTML,请参阅下面的替代解决方案。

  • Using dom

    You can use domto create a <div class="footer"></div>and add content there, for example:

    $("#storages").dataTable({
       dom: '<"top"i>rCt<"footer"><"bottom"flp><"clear">',
       columns: [
          {title: "Name", data: "name"},
          {title: "Size", data: "size"}
       ],
       fnFooterCallback: function(nRow, aaData, iStart, iEnd, aiDisplay) {
          var api = this.api();
          var size = 0;
          aaData.forEach(function(x) {
                size += (x['size']);
          });
          $('.footer').html(size);
       }
    });
    

    See this jsFiddlefor demonstration.

  • Adding <tfoot>

    You can add <tfoot>element with JavaScript beforeinitializing DataTables, then your original code would work without problems.

    However you need to insert correct number of <th></th>elements for each table.

    $("#storages").append('<tfoot><tr><th></th><th></th></tr></tfoot>');
    

    See this jsFiddlefor demonstration.

  • 使用 dom

    您可以使用dom<div class="footer"></div>那里创建和添加内容,例如:

    $("#storages").dataTable({
       dom: '<"top"i>rCt<"footer"><"bottom"flp><"clear">',
       columns: [
          {title: "Name", data: "name"},
          {title: "Size", data: "size"}
       ],
       fnFooterCallback: function(nRow, aaData, iStart, iEnd, aiDisplay) {
          var api = this.api();
          var size = 0;
          aaData.forEach(function(x) {
                size += (x['size']);
          });
          $('.footer').html(size);
       }
    });
    

    请参阅此 jsFiddle进行演示。

  • 添加 <tfoot>

    您可以初始化 DataTables之前<tfoot>使用 JavaScript添加元素,然后您的原始代码将毫无问题地工作。

    但是,您需要<th></th>为每个表插入正确数量的元素。

    $("#storages").append('<tfoot><tr><th></th><th></th></tr></tfoot>');
    

    请参阅此 jsFiddle进行演示。

回答by David says reinstate Monica

One means of doing this is the following – though I can't necessarily claim it to be 'the smartest':

这样做的一种方法如下——尽管我不一定声称它是“最聪明的”:

fnFooterCallback: function (nRow, aaData, iStart, iEnd, aiDisplay) {
    // getting a reference to the <table> itself (as a jQuery object):
    var table = this;
    var api = table.api();
    var size = 0;
    aaData.forEach(function (x) {
        size += (x['size']);
    });

    // finding the number of cells in the row with the largest
    // number of cells (for later use as a colspan attribute,
    // assuming that you want only one cell in the <tr> of the
    // footer).
    // first finding all <tr> elements within the <table>,
    // using get() to convert that collection to an array:
    var maxColumnLength = table.find('tr').get()
    // using Array.prototype.reduce() to compare
    // the length (size) of each row's cells collection:
                          .reduce(function (a, b) {
    // keeping the current <tr> (a) if its cells.length
    // is larger than the currently-assessed <tr> (b):
                              return a.cells.length > b.cells.length;
    // finding the number of cells contained in the
    // <tr> that has the largest collection of cells:
                          }).cells.length;

    // setting the tfoot variable to *either* the current
    // <tfoot> element (if one might exist from being
    // previously created), or creating
    // a <tfoot> if one does not already exist:
    var tfoot = this.find('tfoot').length ? this.find('tfoot') : $('<tfoot>', {
    // setting the innerHTML of the created-<tfoot>:
        'html': '<tr><td class="result" colspan="' + size + '"></td></tr>'
    // inserting it before the first <tbody> element:
    }).insertBefore($(this).find('tbody'));

    // finding the <td> element with the class of 'result'
    // (obviously adjust to taste), and setting its text:
    tfoot.find('td.result').text(size);
}

JS Fiddle demo.

JS小提琴演示

References:

参考: