使用jQuery添加新行时如何刷新简单的Datatables表 [英] How to refresh a simple Datatables table when adding new rows with jQuery

查看:505
本文介绍了使用jQuery添加新行时如何刷新简单的Datatables表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为这很简单,但是找不到与ajax加载的数据或数组中提供的数据无关的引用.我在具有以下基本代码的现有HTML表格上使用DataTables:

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?

如何通知DataTables有关新行?

How do I inform DataTables about the new rows?

推荐答案

经过几次实验,由于DOM表的文档和示例不是很清楚,因此您可以使用相同的row.add()方法添加HTML TR s,就像处理对象和数组一样.然后,您调用 draw()方法使更改可见:

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:

例如

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

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

不幸的是,它确实允许您刷新使用jQuery所做的添加(理想情况下,这是我真正想要允许透明使用DataTables的内容):(

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) :(

最终解决方案(目前):

我添加了一个自定义的appendRow() jQuery扩展,该扩展检查该表是否为DataTable并在需要时通过DataTables api重定向追加:

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/

这篇关于使用jQuery添加新行时如何刷新简单的Datatables表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆