首页 > 解决方案 > 无法在带有 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 在页面上显示实际消息。但是,搜索完成后,页面会显示我的完成消息。

我应该检查什么来解决这个问题?有人遇到过这个问题吗?谢谢。

标签: javascriptjqueryeventsdatatablesevent-listener

解决方案


我最终在搜索中使用了 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);

  

推荐阅读