Javascript 如何在datatable中添加新行并对每行的索引重新排序?
我在datatable中添加了一个新行,并且它工作正常,我通过一个字段(即时间戳)对表进行排序,这意味着新创建的行应该有索引0,并且行应该是1,2,3。。。 但是问题是,当我检查新行的索引时,新行给出了-1。那么,当我添加新行时,如何对表重新排序,以便新创建的行应该具有索引0Javascript 如何在datatable中添加新行并对每行的索引重新排序?,javascript,jquery,datatables,Javascript,Jquery,Datatables,我在datatable中添加了一个新行,并且它工作正常,我通过一个字段(即时间戳)对表进行排序,这意味着新创建的行应该有索引0,并且行应该是1,2,3。。。 但是问题是,当我检查新行的索引时,新行给出了-1。那么,当我添加新行时,如何对表重新排序,以便新创建的行应该具有索引0 var myTable = $('#myTable').DataTable(); var rowNode = myTable
var myTable = $('#myTable').DataTable();
var rowNode = myTable
.row.add([ btnHtml1, btnHtml ])
.draw();
添加索引后检查索引时:
rowindex = tr.index(); //this gives -1 for the newly created row
有人能提出为什么它给出了错误的索引吗?
更新:
function myFunction(this_) {
var tr = $(this_).closest("tr");
rowindex = tr.index(); //this gives the displayed index of the row, NOT the real index
}
我从datatable行调用它,如下所示:
<td>
<button type="button" id="edit_button" onclick='myFunction(this)' name="edit_button">Edit</button>
</td>
{ "firstName": "Airi Satou", "index": "4" }
编辑
我无法重现您的问题
但是我不确定tr
变量是在哪里定义的-因此,这可能会引起问题
对于一个简单的测试,以下是一些数据:
<table id="example" class="display dataTable cell-border" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Row Index</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>0</td>
</tr>
<tr>
<td>Garrett Winters</td>
<td>1</td>
</tr>
<tr>
<td>Ashton Cox</td>
<td>2</td>
</tr>
<tr>
<td>Cedric Kelly</td>
<td>3</td>
</tr>
<tr>
<td>Airi Satou</td>
<td>4</td>
</tr>
<tr>
<td>Haley Kennedy</td>
<td>5</td>
</tr>
</tbody>
</table>
这将在浏览器控制台中生成以下输出:
在这里,我们可以看到“Quinn Flynn”的行具有预期的索引:6
更新
根据答案中的评论,还有一些补充说明:
console.log(table.row().data());
在我的示例中,这将返回一个数组:
[ "Airi Satou", "4" ]
它之所以有效,是因为它使用的是row()
-而不是rows()
,因此默认情况下只从显示的表中获取一行(第一行!)
请注意,如果您将数据作为对象提供,则可能无法获得像我的示例那样的数组-您可能会获得对象-例如,类似以下内容:
<td>
<button type="button" id="edit_button" onclick='myFunction(this)' name="edit_button">Edit</button>
</td>
{ "firstName": "Airi Satou", "index": "4" }
非常感谢。但我是按时间戳排序的,所以根据您的示例,索引会改变它们的顺序,我认为索引永远不会改变。那么,我应该如何从按时间戳排序的表中获取第一行(不管它有什么索引)?我在我的答案中添加了一些注释-我希望它们有助于回答您的问题。再次感谢!改变了我的方法。我现在想要的是真实的索引,而不是显示的表的索引。那么,当我点击一行上的按钮(不是点击该行,而是点击按钮)调用
函数myFunction(){}
,我怎么才能真正得到一行的索引呢?有一些现有的答案可能会帮助你-看看So,看看DataTables论坛。我可能还遗漏了其他问题。@B.S.-如果这些都没有帮助,我想你可能想问一个新问题,以及你新方法的所有相关细节。