【发布时间】:2017-03-14 14:08:29
【问题描述】:
根据says on the tin 的说法,数据表应该能够“在数据重新加载时保留行选择”。但是当使用来自 ajax 的数据时,我无法让它工作。
以下是我制作桌子的方法:
oTable = $('#fileList').DataTable({
select: true,
"ajax": {
"url": "./data.php",
"type": "GET"
},
rowId: 'Index',
"createdRow": function (row, data, dataIndex) {
$(row).addClass(data[2]); //set formatting from data[2]
}
});
按照上面参考资料中的说明,我最初使用它每五秒刷新一次表格:
setInterval(function () {
oTable.ajax.reload();
}
但任何选定的行都会每五秒取消一次选择。所以我尝试更明确:将选定的行加载到数组中并在 setInterval 函数中重新选择它们:
setInterval(function () {
var selectedRows = [];
//put all the selected rows into an array:
sel = oTable.rows('.selected').every(function (rowIdx) {
selectedRows.push(rowIdx);
});
oTable.ajax.reload();
console.log(selectedRows);
//select all the rows from the array
for (var i = 0; i < selectedRows.length; i++) {
console.log("selecting ",selectedRows[i]);
oTable.rows(selectedRows[i]).select();
}
}, 5000)
});
如果我有一个选定的行(在本例中为第三行),我会在控制台中看到:
Array [ 2 ]
selecting 2
正如预期的那样,但未重新选择行。如果我在控制台中输入oTable.rows(2).select();,它会选择第三行,但它在setInterval 块中不起作用。
我猜它可能与 rowID 属性有关。我在 HTML 中定义了这样的表:
<table id="fileList" class="display">
<thead>
<tr>
<th>Index</th>
<th>Status</th>
<th>Owner</th>
</tr>
</thead>
</table>
数据来自一个 php 脚本,该脚本返回一个类似的数组
{"data":[["1", "foo", "bar"], ["2", "fuz", "baz"]}
第一项是索引。
【问题讨论】:
标签: javascript ajax datatables