时间:2019-02-20 13:48:11

标签: javascript jquery datatables

我将数据表与websocket连接起来,以显示来自后端的实时数据。数据是实时供稿,因此该行被连续添加。

问题::如何制作数据表以删除旧数据(例如达到1000行),因此在一个表中仅显示1000行?

1 个答案:

答案 0 :(得分:3)

您可能会监听preDraw事件,该事件恰好在您向其中推送新数据时在重绘数据表之前触发。因此,您可以检查是否超过了行数并查找并删除了最早的条目。

这可能有用,我猜:

//define initial data sample
const srcData = [{parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}];
//define datatable object
const dataTable = $('#mytable').DataTable({
  sDom: 't',
  data: srcData,
  columns: [
    {title: 'parameter', data: 'parameter'},
    {title: 'value', data: 'value'},
    {title: 'timestamp', data: 'timestamp'}
  ]
});
//emulate new data insertion
const dataPooler = window.setInterval(function(){
	dataTable.row.add({parameter: 'CPU usage, %', value: Math.floor(Math.random()*100), timestamp: (new Date()).toString()}).draw();
},3000);
//listen for new draws, purge oldest entry
dataTable.on('preDraw', function(){
	if(dataTable.rows().count() < 5) return;
  //grab the oldest entry timestamp
	let oldestTimestamp = dataTable.column(2).data().toArray().map(entry => new Date(entry)).sort()[0].toString();
	//look through the table and purge corresponding entry if table has more than 10 entries
	let oldestEntryIndex = dataTable.column(2).data().indexOf(oldestTimestamp)
	dataTable.row(oldestEntryIndex).remove();
});
<!doctype html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
    <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  </head>
  <body>
    <table id="mytable"></table>
  </body>
</html>