我正在像这样替换行项目:
var $targetRow = $(entity.row),
dataTable = $targetRow.closest('table.dataTable').DataTable();
dataTable.row($targetRow).remove();
dataTable.row.add({ foo: 1 }).draw();
我在绑定(bind)到表的 rowCreated
回调中有逻辑,因此我正在重新创建行以使用它。这很好用。但是 row.add
总是将重新生成的行添加到列表的最后。有什么办法可以将它插入到特定的索引中吗?
最佳答案
dataTables 将其行保存在索引数组中,并且没有用于在特定索引处添加新行或更改行的 index()
的 API 方法。
这实际上很有意义,因为典型的 dataTable 总是根据数据而不是静态索引进行排序/排序或过滤。当您从服务器接收数据,或想将数据传递给服务器时,您也永远不会使用静态客户端 index()
。
但是如果您考虑一下,您仍然可以对行进行重新排序,并且通过代码非常容易地在特定索引处插入一行,只需对数据进行重新排序即可。添加新行时,将最后一行(插入的行)的数据交换到倒数第二行,然后将倒数第二行的数据交换到倒数第三行,依此类推,直到到达所需的索引插入行。
[0][1][2][3][4->][<-newRow]
[0][1][2][3->][<-newRow][4]
[0][1][2->][<-newRow][3][4]
例如,在单击鼠标的索引处插入一个新行:
$("#example").on('click', 'tbody tr', function() {
var currentPage = table.page();
//insert a test row
count++;
table.row.add([count, count, count, count, count]).draw();
//move added row to desired index (here the row we clicked on)
var index = table.row(this).index(),
rowCount = table.data().length-1,
insertedRow = table.row(rowCount).data(),
tempRow;
for (var i=rowCount;i>index;i--) {
tempRow = table.row(i-1).data();
table.row(i).data(tempRow);
table.row(i-1).data(insertedRow);
}
//refresh the current page
table.page(currentPage).draw(false);
});
关于javascript - DataTables row.add到特定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30712227/