[英]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.