简体   繁体   中英

How to get last inserted row from a datatable

I'm using datatables plugin to create a datatable. I've put a button to add new rows. The new inserted row can be anywhere depends on which column the table is sorted by. I need to set an event to the button inside the row once it is inserted. So I have to get the last inserted row to do so. But I can't find a way. I've tried below but it's not working. index() does not returning exact index where the row really is.

var row = table.row.add({...});
row.draw();
var tr = $('#datatable tbody tr').get(row.index());

Please help. Your answer is kindly appreciated and thank you in advance.

取表的长度和-1 ,该数字是最后一个trindex

var lastRowIndex = $('#datatable tr').length -1;

New rows will be appended onto the end of the row list, so you can do something like this

table.row(table.rows().count()-1)

See fiddle here .

Can't find a way to this using any plugin's provided function. But thank God there's a workaround.

Flag the inserted row in column rendering function. For example, I append a tag

datatable = $('#datatable').DataTable({columns : [{render : function(){... <last/> ...}}]});

On inserting new row, insert it with a data that indicate the flag inclusion. Get the row by the flag. And then remove the flag.

datatable.row.add({...}).draw();
var row = $('last').parents('tr');
$('last').remove();

For any other case which don't need to edit the <tr> explicitly, get the index of last inserted row. Get the datatable row and update the data. Set column render function to render the updated row accordingly.

var i = datatable.rows().count() - 1;
var data = datatable.row(i).data();
datatable.row(i).data(changeSomething(data)).draw();

And to remove the row

datatable.row(i).remove().draw();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM