DataTables row.add 到特定索引 [英] DataTables row.add to specific index

查看:12
本文介绍了DataTables row.add 到特定索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm replacing row items like this:

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

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

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

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

I have logic in the rowCreated callback bound to the table, thus I'm recreating the row to make use of it. This works fine. But row.add always adds the regenerated row last in the list. Is there any way to insert it into a specific index?

推荐答案

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

dataTables holds its rows in an indexed array, and there is no API methods for adding a new row at a specific index or change the index() of a row.

这实际上很有意义,因为典型的 dataTable 总是按数据排序/排序或过滤,而不是静态索引.并且当您从服务器接收数据,或者想要将数据传递给服务器时,您也永远不会使用静态客户端 index().

That actually makes good sense since a typical dataTable always is sorted / ordered or filtered on data, not the static index. And when you receive data from a server, or want to pass data to a server, you never use the static client index() either.

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

But if you think about it, you can still reorder rows and by that insert a row at a specific index very easy by code, simply by reordering the data. When a new row is added, swap the data from the last row (the inserted row) to the second last row, then swap data from the second last row to the third last row and so on, until you reach the index where you want to insert the row.

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

例如,在鼠标点击的索引处插入一个新行:

Example, inserting a new row at the index where the mouse is clicked :

$("#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/

demo -> http://jsfiddle.net/mLh08nyg/

这篇关于DataTables row.add 到特定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆