Javascript 将行追加到DataTables网格

Javascript 将行追加到DataTables网格,javascript,jquery,ajax,datatables,Javascript,Jquery,Ajax,Datatables,我试图将标记动态添加到DataTable中,但是我没有找到关于“AddingTR过程”应该如何工作的真正好的文档。我将此作为我的DataTables设置: $("#Grid").DataTable({ stateSave: true, fixedHeader: true, rowReorder: true, . . columnDefs: [ { orderable: false, className: "seq-cell", targets: 0

我试图将
标记动态添加到DataTable中,但是我没有找到关于“AddingTR过程”应该如何工作的真正好的文档。我将此作为我的DataTables设置:

$("#Grid").DataTable({
   stateSave: true,
   fixedHeader: true,
   rowReorder: true,
   .
   .
   columnDefs: [
      { orderable: false, className: "seq-cell", targets: 0 },
      { orderable: false, targets: "_all" }
   ]
})
.on("row-reordered", function (e, diff, edit) {
   for (var i = 0; i < diff.length; i++)
   {
       ..
   }
});

“d”参数是一行的HTML;我把它附在身体上。这样可以正确添加,但没有启用行重新排序功能。向DataTable追加数据,然后重新启用任何功能的正确方法是什么?

最好的选择是使用Datatables API向表中添加行。如前一响应中所述,您可以使用或。数据需要位于与Datatables数据结构配置(即数组或对象)匹配的数据结构中

但是,看起来您正在接收HTML结构化数据并直接附加到表中。在这种情况下,Datatables不知道添加的数据。您需要销毁()Datatables表,追加数据,然后重新初始化Datatables。例如:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().destroy();
       var $body = $("#Grid tbody");
       $body.append(d);

       $("#Grid").DataTable({
       stateSave: true,
       fixedHeader: true,
       rowReorder: true,
       .
       .
       columnDefs: [
          { orderable: false, className: "seq-cell", targets: 0 },
          { orderable: false, targets: "_all" }
       ]
    })

    }
});
$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().row.add($(d).get(0)).draw();
    }
});
使用API方法添加新行,而不是追加到表体

如果
d
包含以下格式的字符串
..
,则可以使用
$(“#网格”).DataTable().row.add($(d).get(0))
添加新行

例如:

$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().destroy();
       var $body = $("#Grid tbody");
       $body.append(d);

       $("#Grid").DataTable({
       stateSave: true,
       fixedHeader: true,
       rowReorder: true,
       .
       .
       columnDefs: [
          { orderable: false, className: "seq-cell", targets: 0 },
          { orderable: false, targets: "_all" }
       ]
    })

    }
});
$.ajax({
    type: "post",
    url: "AddItem",
    data: $("#newitemform").find(":input[name]").serialize(),
    success: function (d) {
       $("#Grid").DataTable().row.add($(d).get(0)).draw();
    }
});

有关代码和演示,请参阅。

ajax中返回的行的html是否有所不同?或者只是html中的数据在变化?返回的html总是TR元素,但只随数据而变化,而不是语法……没有必要破坏表,
row.add()
API方法接受
TR
节点作为参数。@Gyrocode.com是的,我使用它获得了一些成功(这个叉子说明了这是通过:)但是由于某种原因,在我的确切情况下,它仍然不起作用,这真的很奇怪……所以这种方法现在解决了它。@BrianMains,我忘记了链接
draw()
方法,看看它在哪里起作用。我仍然相信没有必要
destroy()
表。也更新了。正如@Gyrocode.com提到的,不需要使用
destroy()
方法。如果您的数据结构与表结构匹配,他的示例应该可以正常工作。直到现在,我才意识到
row.add()
将以
的格式追加数据。很高兴知道这一点。