【问题标题】:DataTables row.add to specific indexDataTables row.add 到特定索引
【发布时间】:2015-08-23 02:26:06
【问题描述】:

我正在替换这样的行项目:

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

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

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

我在绑定到表的rowCreated 回调中有逻辑,因此我正在重新创建行以使用它。这工作正常。但是row.add 总是将重新生成的行添加到列表的最后。有没有办法将它插入到特定的索引中?

【问题讨论】:

标签: javascript jquery datatables


【解决方案1】:

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);
});  

演示 -> http://jsfiddle.net/mLh08nyg/

【讨论】:

  • 如果您在 tr/td 元素上有自定义类名或数据属性,这将不起作用。至少我想不通。
【解决方案2】:

另一种方法是插入行,然后将DataTable行数组中的行移动到重绘Table之前指定的位置:

// 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-23
    • 2017-07-23
    • 2018-12-04
    • 2014-03-26
    • 2016-10-28
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多