如何覆盖HTML数据表上的数据



在模板上,我从Websocket连接接收数据,以下是我接收数据的方式:

<script language="javascript">
mySocket.onmessage = function(event) {
var data = JSON.parse(event.data);
console.log('data', data);
$('history').append('</td><td>'+data['Rate']+'</td><td>'+data['Quantity']+'</td></tr>')
};
</script>

在我的HTML上,我有一个数据表:

<table class=" table table-hover" id="history">
<thead>
<tr>
<th>RATE</th>
<th>QUANTITY</th>
</tr>
</thead>
<tbody>

每次我收到消息时,消息的内容都会附加到表中。这段代码运行起来没有任何问题,问题是它会不断向表中添加数据,使表变得又大又难看。

相反,我想要的是:该表保持10条记录的固定高度,因此每次接收到新消息时,该消息都会附加在该表的第一行,并且位于该表第十位的消息会消失。有办法做到这一点吗?提前谢谢。

也许您的代码不起作用。

更改如下。

<table class=" table table-hover" id="history">
<thead>
<tr>
<th>RATE</th>
<th>QUANTITY</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script language="javascript">
mySocket.onmessage = function(event) {
var data = JSON.parse(event.data);
console.log('data', data);
$('#history > tbody').prepend('<tr><td>'+data['Rate']+'</td><td>'+data['Quantity']+'</td></tr>');
if ($('#history > tbody > tr').length > 10) {
$('#history > tbody > tr:last-child').remove();
}
};
</script>

var ind = 0;
setInterval(function () {
ind++;
$('#history > tbody').prepend('<tr><td>aaa' + ind + '</td><td>bbb</td></tr>');
if ($('#history > tbody > tr').length > 10) {
$('#history > tbody > tr:last-child').remove();
}
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table class=" table table-hover" id="history">
<thead>
<tr>
<th>RATE</th>
<th>QUANTITY</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</body>
</html>

最新更新