javascript - Datatables - 当滚动接近表格底部时,如何创建侦听器?
问题描述
我目前正在使用 datatablesJS(来自https://datatables.net/)来显示来自分页数据库的结果数组。因此,在初始加载时,用户会获得索引 0 和 100 行。
我正在尝试编写一个函数,以便当用户滚动到表格底部附近时,它将查询更多表格并将结果附加到当前数据数组中。我有查询设置,但我不知道有一个 jquery 或 datatablesJS 函数来监听滚动到其最大滚动长度底部的距离。有什么建议么?
注意:这个问题似乎类似于On dataTable scroll data should load from server side and append to existing records,但不同的是我只想在用户滚动到底部时查询。这篇文章以及我在 DataTables 文档上看到的内容是,他们运行超时,直到他们使用 Datatables 的 ajax 参数获取所有数据。
解决方案
您需要一个函数来检测用户何时滚动到表格底部,并需要另一个函数来获取下一行数据。
这个演示应该给你一些关于如何做到这一点的提示。
$(function() {
var $mytable = $("#myTable");
var count = 3; //initial number of rows
var max = 50; //max number of rows (just for demo)
var $datatable = $mytable.DataTable({
"paging": false,
"bFilter": false
}); //init the datatable and return a refence to it
//listen for scroll and resize and custom 'fetchmore' events
$(window).bind('scroll resize fetchmore', function() {
var viewportHeight = window.innerHeight;
var scrolltop = $(window).scrollTop();
var bottomOfTable = $mytable.offset().top + $mytable.outerHeight();
//console.log(viewportHeight, scrolltop, bottomOfTable);
if ($(window).scrollTop() + viewportHeight >= bottomOfTable) {
if (count < max) {
//console.log("Fetch more data!");
load_more();
$(window).trigger("fetchmore"); //keep triggering this event until we've filled the viewport
}
}
});
function load_more() {
//fetch more data here
count++;
$datatable.row.add([
count + '.1',
count + '.2 (loaded@' + Date.now() + ')'
]).draw(false);
}
//trigger initial fetch
$(window).trigger("fetchmore");
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
</head>
<body>
<table id="myTable" class="display">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.1</td>
<td>1.2 (initial row)</td>
</tr>
<tr>
<td>2.1</td>
<td>2.2 (initial row)</td>
</tr>
<tr>
<td>3.1</td>
<td>3.2 (initial row)</td>
</tr>
</tbody>
</table>
</body>
推荐阅读
- excel - 随机化基诺卡
- javascript - 从数据属性中动态获取值
- sql - 查询日期列的 MAX 和另一列的 COUNT
- php - 如果它们来自同一个域,使用 file_get_contents() 访问多个 URL 的有效方法?
- python - 如何检查某些字符是否不在字符串中?
- kubernetes - 如果 kubernetes 已经跟踪它,为什么我应该将 kubernetes 部署配置存储到源代码管理中?
- rxjs - 如何根据密钥加入流
- ruby-on-rails - 选择所有关联都存在的记录
- translation - 在凤凰应用程序中使用gettext与数据库中的内容?
- c# - DataGridColumn 不调整大小