gpt4 book ai didi

javascript - 将数据添加到 DataTables 表时无法更改页面

转载 作者:行者123 更新时间:2023-11-30 19:38:56 24 4
gpt4 key购买 nike

我有一个 dataTables 表并向其中添加了大量行。我希望能够在添加数据时使用表格。

问题是 DataTables 代码在每次执行 .draw() 时都会重建分页 block ,这与传递给函数的参数无关。

目前,我通过“侵入”aoDrawCallback 列表并拦截 pagination 回调来部分解决了这个问题。添加行时,我允许在页码或总页数更改时重新绘制分页 block 。

await sleep(..); block 提供了 2 个特性:

  • 它允许在 for 循环执行期间重绘表格;
  • 它足够延迟代码,因此用户可以在重绘之前单击分页按钮(即使考虑到现在我们重绘它们的频率降低了 10 倍 - 取决于 show X entries 值)<

根据表的复杂性, sleep 值(以毫秒为单位)可以减少到 1。

请参阅下面和 JSFIddle 中的代码

我的解决方案的一个缺陷是我们在每个循环上浪费了 sleep 时间。你能提供更好的解决方案吗?

谢谢。

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}

var oldPaginationCb;
var prevPage=-1, prevPages=-1;
var isCustomPaginationEnabled = false; //Our custom actions are disabled by default

function myPaginationCb ( settings ) {
var
start = settings._iDisplayStart,
len = settings._iDisplayLength,
visRecords = settings.fnRecordsDisplay(),
all = len === -1,
page = all ? 0 : Math.ceil( start / len ),
pages = all ? 1 : Math.ceil( visRecords / len );
if (! (isCustomPaginationEnabled && page === prevPage && pages === prevPages)) {
prevPage = page;
prevPages = pages;
return oldPaginationCb(settings);
}
}

console.log('started');
var values = [...Array(500).keys()]

var commentTable = $('.commentTable').DataTable();

var dtApi = $('.commentTable').dataTable();

//Replacing the pagination draw callback function
var paginationCallback = dtApi.fnSettings().aoDrawCallback.filter(cb => { return cb.sName === "pagination" })[0];
oldPaginationCb = paginationCallback.fn;
paginationCallback.fn = myPaginationCb;


$('.addComment').on('click', async function () {
isCustomPaginationEnabled = true;
for(var i=0; i<values.length; i++) {
commentTable.row.add(
[
'Date',
'User',
i,
]
).draw(false);
await sleep(50);
}
isCustomPaginationEnabled = false;
});
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<div><strong>
Click Start, then try using the table navigation buttons
</strong></div>
<button class="addComment">
Start
</button>
<table class='commentTable'>
<thead>
<th>Date</th>
<th>User</th>
<th>Comment</th>
</thead>
<tbody>
</tbody>
</table>

最佳答案

调用draw() API 方法仅在 for 循环之外执行一次。例如:

for(var i=0; i<values.length; i++) {
commentTable.row.add(
[
'Date',
'User',
i,
]
);
}
commentTable.draw();

根据 official documentation :

A draw is not performed automatically by most DataTables API actions to allow grouping of actions (for example adding multiple rows is more efficient if you group them).

参见 updated example用于代码和演示。

关于javascript - 将数据添加到 DataTables 表时无法更改页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55619145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com