javascript - 无法在带有 DataTables 的 search.dt 搜索事件中使用 html() 以添加加载消息
问题描述
我正在使用DataTables并为事件添加了一个侦听器,search.dt
目的是在执行搜索时显示加载消息,然后在调用一次时删除该消息(或在测试时显示搜索完成消息)draw.dt
。
我分别为每个事件成功地将消息记录到控制台,但由于某种原因,draw.dt
我只能成功更新 DOM 以显示消息。我使用了相同的代码,search.dt
但我没有看到我试图修改以显示加载消息的 HTML 有任何变化。见下文。
let table = $('#product-table').on( 'search.dt', function () {
$('#form-feedback').html('Searching...'); // this DOESN'T WORK
console.log('searching...'); // this works
} ).on( 'draw.dt', function () {
$('#form-feedback').html('Done.'); // this works
console.log('done searching.'); // this works
} ).DataTable({
"lengthMenu": [10,20,25,50,100],
"pageLength": 25,
"order": [[ 7, "desc" ]],
"stripeClasses":["even","odd"],
"responsive": true,
"dom": 'lrtip',
"columnDefs": [
{ "visible": false, "targets": [4,5,6,7] }
]
});
每当运行新搜索时,控制台都会记录我的searching...
消息,但不会根据我尝试更新的 HTML 在页面上显示实际消息。但是,搜索完成后,页面会显示我的完成消息。
我应该检查什么来解决这个问题?有人遇到过这个问题吗?谢谢。
解决方案
我最终在搜索中使用了 debounce,并且似乎通过searching...
在 debounce 函数中显示我的消息来使其正常工作。我猜这个问题与search.dt
立即触发重绘表格或其他事件的事件有关。我使用了 Lodash debounce,下面的解决方案给了我想要的东西。如果他们走类似的路线,也许这对其他人有用。
var query = undefined;
// when search input changes...
$('#search-input').keyup( function () {
// if there's been no change to the field then do nothing
if (query === this.value) {
return;
}
// update with the value entered
query = this.value;
/* Wait until at least 2 characters have been entered, or user has cleared the input */
if (this.value.length >= 2 || (!this.value)) {
// run our debounce search function
debouncedSearchDraw(query);
}
} );
// the debounce search function
var debouncedSearchDraw = debounce(function(val) {
// successfully display searching message to user
$('#form-feedback').html('Searching...');
// search and redraw the table with the results
table.search(val).draw();
// after drawing the table remove the searching message
$('#form-feedback').html('');
}, 750);
推荐阅读
- c# - 根据底层图像的颜色创建一个三角形填充位图
- c# - web API - 多种形式的数据
- performance - 如何提高程序的性能?
- spring-kafka - 使用 @StreamListener 时,对 KafkaListenerContainerFactory 的自定义会反映在生成的 KafkaMessageListenerContainer 中吗?
- ios - 如何在 Xcode 中追踪此错误消息“找不到上传服务器”?
- http - Go Lang:非常简单的 HTTP Post 请求和响应端点
- batch-file - 启动批处理文件时如何获取用户输入以及如何将输入分成不同的变量
- android - FirebaseUI 电子邮件在启动时启动电子邮件登录流程
- r - 为什么对同一向量的两个引用会为向量的每个元素返回不同的内存地址?
- android - 始终以欧洲字母在 Android 中获取 GMT 时间