如何覆盖数据表上的数据? [英] How can I overwrite data on Datatables?
问题描述
在模板上,我有一个websocket连接,该连接每秒发送一次页面数据.因此,每秒钟都会收到一个新的数组数组,如下面的数组,只是具有不同的值.我正在尝试在数据表上显示此数据. 问题是我需要覆盖表上的数据,因此,每当我收到新的数组数组时,表上的先前数据都必须被新记录覆盖.
On a template, I have a websocket connection which sends to the page data every second. So every second a new array of arrays like the one below is received, just with different values. I'm trying to show this data on a datatable. The problem is that I need to override the data on the table, so every time I receive a new array of arrays, the previous data that was on the table must be overwritten with the new records.
var data = [
[1, 5],
[9, 3],
[71.55, 17],
[1800, 20],
[713, 3],
]
这是我尝试过的:
$.each(data, function(key,value) {
$('#mytable').append('<tr><td>'+value[0]+'</td><td>'+value[1]+'</td></tr>')
})
此代码的问题在于,尽管它将正确显示数据,但每次我收到一个新数组时,它都不会追加旧数组,而只是覆盖数据.
The problem with this code is that, although it will show the data correctly, every time I receive a new array, instead of overwriting the old one it will just append the data.
我也尝试过:
$.each(data, function(key,value) {
$('#mytable').html('<tr><td>'+value[0]+'</td><td>'+value[1]+'</td></tr>')
})
但是这行不通,因为它只会循环遍历整个数组,并且一次仅显示该数组的一条记录.
But this is not going to work, since it will only loop through the array and only show one record of the array at time.
这是桌子:
<table id="mytable" class="pos-table table table-striped table-hover">
<thead>
<tr>
<th>RATE</th>
<th>AMOUNT</th>
</tr>
</thead>
</table>
推荐答案
您必须在变量中生成dataTable,然后可以销毁它,添加行,然后在变量中再次创建dataTable
You must generate the dataTable in a variable, then you can destroy it, add the rows and again in the variable create the dataTable
tb.destroy();
// insert rows
tb=$('#mytable').DataTable();
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.20/js/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="mytable" class="pos-table table table-striped table-hover">
<thead>
<tr>
<th>RATE</th>
<th>AMOUNT</th>
</tr>
</thead>
</table>
<button onclick="add();">add</button>
</button>
<script>
var data = [
[1, 5],
[9, 3],
[71.55, 17],
[1800, 20],
[713, 3],
]
var tb = $('#mytable').DataTable();
$(document).ready(function() {
add();
});
function add(table) {
tb.destroy();
$.each(data, function(key, value) {
$('#mytable').append('<tr><td>' + value[0] + '</td><td>' + value[1] + '</td></tr>')
})
tb = $('#mytable').DataTable();
}
</script>
</body>
</html>
这篇关于如何覆盖数据表上的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!