【问题标题】:Jquery datatable add new row at specified indexJquery数据表在指定索引处添加新行
【发布时间】:2013-05-14 14:55:25
【问题描述】:

是否有可能在 Jquery 数据表中的第 2/3/...n 行之后添加新行? 我使用了这种方法 fnAddData([...])。 它按预期工作。 但我需要在两行之间添加记录。 请任何人帮助我..

【问题讨论】:

  • 你能创建一个 jsFiddle 来显示问题吗?
  • datatables.net/forums/discussion/11899/… 他建议“启用排序,但禁用用户排序并使用 aaSortingFixed 强制排序始终发生在隐藏列 - 您的索引列上。然后当您插入新行时,请阅读您要在之后插入新行的行的排序索引,并将新行的排序索引设置为高一。因此它将被插入到正确的位置:-)。您还需要遍历所有行,并为高于插入点的现有行增加排序索引"

标签: jquery datatable


【解决方案1】:

我与你分享我所做的:

// for example you want to insert after the 2nd row
var numberOfRowAfterYouWantToInsert = 2;
var rowAfterYouWantToInsert = $("#yourTableId tr").eq( numberOfRowAfterYouWantToInsert );
var rowsAfter_rowAfterYouWantToInsert = rowAfterYouWantToInsert.nextAll();
var standbyTable = $("<table>");
// remove rows by putting over to a standby table
standbyTable.append( rowsAfter_rowAfterYouWantToInsert );
// just did an empty tr here
var tr = $("<tr>");
// append it
$("#yourTableId").append( tr );
// and put back those removed rows to the original table
$("#tableID").append( rowsAfter_rowAfterYouWantToInsert );

这个解决方案简单易读,主要优点是:它有效 :) 希望对您有所帮助!

编辑: 我发现有一个更简单的解决方案:

// for example you want to insert after the 2nd row
var numberOfRowAfterYouWantToInsert = 2;
var rowAfterYouWantToInsert = $("#yourTableId tr").eq( numberOfRowAfterYouWantToInsert );
// new row with two cells
var tr = $("<tr><td>asd</td><td>qwe</td></tr>");
rowAfterYouWantToInsert.after( tr );

【讨论】:

  • 它不适用于 Jquery 数据表。当您对表格进行排序时,该行将丢失。
  • @LucioFonseca 如果你不使用 $("#yourTableId").trigger("update");添加行后的语句,它会丢失(如果我对排序很了解)
【解决方案2】:

这对我有用。从数据表中获取数组,在所需索引处拼接值,然后重绘数据表。这样,如果您必须重新绘制 - 您附加的值仍将在表中。

var newRow = [1, 2, 3]; // new row in the datatable
var index = 4; // index for the new row to be added
var currentRows = datatable.data().toArray();  // current table data
currentRows.splice(index, 0, newRow);

datatable.clear();
datatable.rows.add(currentRows);
datatable.draw();

【讨论】:

    【解决方案3】:

    将行添加到您的表(其中 tr 它是对您要在行之前插入的表的 DOM 引用):

    var html = "<tr><td>a</td><td>b</td></tr>";
    $(tr).after(html);
    

    接下来,使用此函数重置表(其中 tbServer 是表 id):

    function ResetDataTable() {
        $("#tbServer thead tr").remove();
        var oHeadRow = $(".dataTables_scrollHeadInner").find("table thead tr").clone();
        $("#tbServer thead").append(oHeadRow);
        var oTbl = $("#tbServer").clone();
        oTable.destroy();
        $("#tbServer").remove();
        $("#divTbl").append(oTbl)
        SetupDataTable();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-05
      • 2012-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多