Javascript DataTables行。添加到特定索引

Javascript DataTables行。添加到特定索引,javascript,jquery,datatables,Javascript,Jquery,Datatables,我正在替换行项目,如下所示: var $targetRow = $(entity.row), dataTable = $targetRow.closest('table.dataTable').DataTable(); dataTable.row($targetRow).remove(); dataTable.row.add({ foo: 1 }).draw(); 我将行created回调中的逻辑绑定到表,因此我正在重新创建该行以利用它。这个很好用。但是row.add始终将重新生成

我正在替换行项目,如下所示:

var $targetRow = $(entity.row),
    dataTable = $targetRow.closest('table.dataTable').DataTable();

dataTable.row($targetRow).remove();

dataTable.row.add({ foo: 1 }).draw();

我将
行created
回调中的逻辑绑定到表,因此我正在重新创建该行以利用它。这个很好用。但是
row.add
始终将重新生成的行添加到列表的最后一行。有没有办法将其插入到特定索引中?

dataTables将其行保存在索引数组中,并且没有API方法可用于在特定索引中添加新行或更改行的
索引()

这实际上很有意义,因为典型的dataTable总是根据数据进行排序/排序或筛选,而不是静态索引。当您从服务器接收数据或希望将数据传递给服务器时,您也永远不会使用静态客户端
index()

但是如果您仔细考虑一下,您仍然可以对行进行重新排序,通过代码,只需对数据进行重新排序,就可以很容易地在特定索引处插入一行。添加新行时,将数据从最后一行(插入的行)交换到最后第二行,然后将数据从最后第二行交换到最后第三行,依此类推,直到到达要插入行的索引

[0][1][2][3][4->][<-newRow]
[0][1][2][3->][<-newRow][4]
[0][1][2->][<-newRow][3][4]

演示->另一种方法是插入行,然后将DataTable行数组中的行移动到重新绘制表之前指定的位置:

// Define the row to insert (using your method of choice)
var rowInsert = $('#table-id').find('tr:last');
// Get table reference - note: dataTable() not DataTable()
var table = $('#table-id').dataTable();
// Get api
var dt = table.api();
// Insert row (inserted as the last element in aiDisplayMaster array)
dt.row.add(rowInsert);
// Get the array holding the rows
var aiDisplayMaster = table.fnSettings()['aiDisplayMaster'];
// Remove the last element in the array
var moveRow = aiDisplayMaster.pop();
// EITHER add row to the beginning of the array (uncomment)
//aiDisplayMaster.unshift(moveRow);
// OR add row to a specific index (in this case to index 3)
var index = 3;
aiDisplayMaster.splice(index, 0, moveRow);
// Redraw Table
dt.draw(false);

对这个问题的一些见解:还有一个不太好的解决方法:@AmmarCSE我不认为使用jQuery操作datatable html是一种好方法。它需要跟踪行。。。还是我错了?@filur,哦,对不起,我不知道如何使用数据表。我只是添加了那个链接,因为您在tags@LShetty谢谢,我也看过了。希望有新的解决方案:)
// Define the row to insert (using your method of choice)
var rowInsert = $('#table-id').find('tr:last');
// Get table reference - note: dataTable() not DataTable()
var table = $('#table-id').dataTable();
// Get api
var dt = table.api();
// Insert row (inserted as the last element in aiDisplayMaster array)
dt.row.add(rowInsert);
// Get the array holding the rows
var aiDisplayMaster = table.fnSettings()['aiDisplayMaster'];
// Remove the last element in the array
var moveRow = aiDisplayMaster.pop();
// EITHER add row to the beginning of the array (uncomment)
//aiDisplayMaster.unshift(moveRow);
// OR add row to a specific index (in this case to index 3)
var index = 3;
aiDisplayMaster.splice(index, 0, moveRow);
// Redraw Table
dt.draw(false);