【问题标题】:Add jquery datatables table footer via Javascript without using HTML通过 Javascript 添加 jquery datatables 表页脚而不使用 HTML
【发布时间】:2015-05-16 12:56:16
【问题描述】:

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

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

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

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
        );        
    }
});

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

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

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

【问题讨论】:

  • 您能否在您的问题中添加更多代码/信息,以便我们重现您的问题?并且,如果可能的话,分叉这个JS Fiddle 以重新创建您的用例的近似值?可以使用 JS Fiddle 的“echo”API 包含 AJAX,在另一个 SO 问题“AJAX in jsFiddle”中有一些说明。
  • @DavidThomas 当然,我相应地改变了小提琴,如果一些问题足够好!
  • 如果没有 &lt;tfoot&gt; 元素,您将无法使用 DataTables 添加页脚。那么您是在问如何在不修改 HTML 的情况下做到这一点吗?我假设你无法控制 HTML,对吧?

标签: javascript jquery datatables


【解决方案1】:

原因

如果没有&lt;tfoot&gt; 元素,就无法操作页脚。

解决方案 #1

按照DataTables - Installation 中的说明添加适当的标记。

解决方案 #2

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

  • 使用dom

    您可以使用dom 创建&lt;div class="footer"&gt;&lt;/div&gt; 并在其中添加内容,例如:

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

    请参阅this jsFiddle 进行演示。

  • 添加&lt;tfoot&gt;

    您可以在 初始化 DataTables 之前使用 JavaScript 添加&lt;tfoot&gt; 元素,然后您的原始代码将毫无问题地运行。

    但是,您需要为每个表插入正确数量的 &lt;th&gt;&lt;/th&gt; 元素。

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

    请参阅this jsFiddle 进行演示。

【讨论】:

  • 在我通过 javascript 添加(附加 tfoot)页脚行到表格后,DataTable 列不再扩展(nowrap)并且它们显示固定宽度并且其中的数据换行....
【解决方案2】:

这样做的一种方法是以下 - 虽然我不一定声称它是“最聪明的”:

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.

参考资料:

【讨论】:

    【解决方案3】:

    正如其他答案所说,我需要事先以某种方式定义页脚。不完美,但至少我可以保持我的 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/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      相关资源
      最近更新 更多