[英]How to add a new row in datatable and re order the indexes of each row?
我在数据表中添加了一个新行并且它工作正常,我通过一个字段(即时间戳)对表进行排序,这意味着新创建的行应该有索引 0,行应该是 1,2,3...但是问题是当我检查它的索引时,新行给出了-1。 那么,当我添加新行以使新创建的行的索引为 0 时,如何实际重新排序表?
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
}
我从数据表行中调用它,如下所示:
<td>
<button type="button" id="edit_button" onclick='myFunction(this)' name="edit_button">Edit</button>
</td>
我无法重现您的问题。
但我不确定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>
这是对数据的测试:
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable();
var rowNode = table.row.add( ['Quinn Flynn', '?'] ).draw();
console.log(rowNode.index());
});
</script>
这将6
打印到浏览器控制台 - 正如预期的那样,新行的索引为6
。
验证这一点的另一种方法是遍历所有行,显示每行的索引:
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable();
var rowNode = table.row.add( ['Quinn Flynn', '?'] ).draw();
table.rows().every( function () {
console.log(this.index());
});
});
</script>
这会在浏览器控制台中生成以下 output:
在这里,我们可以看到“Quinn Flynn”的行具有预期的索引: 6
。
更新
基于答案中的评论的一些附加说明:
分配给行的行索引不会改变,一旦它被分配,直到行被删除,或者数据被替换和刷新。
索引值是根据提供给 DataTables 的数据的顺序分配的——例如,在我的情况下,我的 HTML 表中的第一行是“Tiger Nixon”——因此分配了行索引 0。这同样适用于数据由 JSON object 提供。
行索引与行的显示顺序无关(由于排序和/或过滤)。
当您向 DataTables 添加新行时,它会添加到 DataTables 内现有行的末尾 - 并相应地编制索引。 所以,我的新行被分配了索引 6。
听起来您想要获取表中显示的第一行,而不管其索引号是多少。
您可以使用一个快捷方式来获得它:
console.log(table.row().data());
在我的示例中,这将返回一个数组:
[ "Airi Satou", "4" ]
它之所以有效,是因为它使用row()
- 而不是rows()
,因此默认只从显示的表中获取一行(第一行!)。
请注意,如果您将数据作为对象提供,您可能不会得到像我的示例那样的数组 - 您可能会得到 object - 例如,如下所示:
{ "firstName": "Airi Satou", "index": "4" }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.