How to refresh a simple Datatables table when adding new rows with jQuery

我是研究僧i 提交于 2019-12-07 07:22:49

问题


I thought this one would be simple, but I can't find a reference that is not about ajax loaded data or data supplied in an array. I am using DataTables on an existing HTML table with this basic code:

  $('table.wizard').dataTable({
        lengthChange: false,
        iDisplayLength: 100,
        order: [[9, 'desc']]
    });

I am adding rows to a table, dynamically, as data records are found like this:

var $body = $('table.wizard tbody');
$tr = $("<tr>").appendTo($body).attr({ 'id': 'sku' + item.MerchantSKU, 'data-sku': item.MerchantSKU });
// then append the individual tds
[snip]
// Now how to tell the datatables it has changed?

How do I inform DataTables about the new rows?


回答1:


After a few experiments, as the documentation and examples are not very clear for DOM tables, it turns out you can use the same row.add() method for adding HTML TRs as you would for objects and arrays. You then call the draw() method to make the changes visible:

e.g.

dt.row.add($tr);
dt.draw();

JSFiddle: http://jsfiddle.net/TrueBlueAussie/HEDvf/2205/

Unfortunately it does allow you to refresh additions made with jQuery (which is ideally what I really wanted to allow for transparent use of DataTables) :(

Final solution (for now):

I added a custom appendRow() jQuery extension, that checks if the table is a DataTable and redirects the append via the DataTables api if needed:

// Assume we only append to one table at a time (otherwise rows need to be cloned)
$.fn.appendRow = function ($rows) {
    if ($(this).parent().hasClass("dataTables_wrapper")) {
        var dt = $(this).dataTable().api();
        $rows.each(function () {
            dt.row.add(this);
        });
        dt.draw();
    } else {
        $(this).append($rows);
    }
}

JSFiddle: http://jsfiddle.net/TrueBlueAussie/HEDvf/2212/



来源:https://stackoverflow.com/questions/28511128/how-to-refresh-a-simple-datatables-table-when-adding-new-rows-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!