[英]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. index()
不会返回行实际所在的确切索引。
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
,该数字是最后一个tr
的index
var lastRowIndex = $('#datatable tr').length -1;
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.对于不需要显式编辑
<tr>
任何其他情况,获取最后插入行的索引。 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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.