Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

javascript - DataTables row.add to specific index

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...