【问题标题】:jQuery datatable retain filter parameter after refresh刷新后jQuery数据表保留过滤器参数
【发布时间】:2016-05-04 14:17:39
【问题描述】:

根据我之前的一些问题,我正在使用数据表。我能够在表格顶部添加 INPUT 字段,以便在数据表中进行单独的列搜索。

我现在需要做的是在页面刷新后保留在INPUT字段(或字段)中输入的参数。

到目前为止,这是我的代码:

 // header input filters
 $('#example1 .filters th').each(function(){
   var title = $('#example1 thead th').eq($(this).index()).text();
   $(this).html('<input type="text" placeholder="Search '+title+'" />');
 });

 // set and print the datatable
 var $dataTable = $('#example1').DataTable({
   "ajax": 'api/dateset.php',
   "iDisplayLength": 25,
   "order": [[ 6, "desc" ]],
   "scrollY": 580,
   "scrollX": true,
   "bDestroy": true,
   "stateSave": true
 });

 // Apply the search to columns
 $dataTable.columns().eq(0).each(function(colIdx){
   $('input', $('.filters th')[colIdx]).on('keyup change', function(){
     $dataTable
       .column(colIdx)
       .search(this.value)
       .draw();
   });
 });

如果您注意到我在上面设置 $dataTable 的部分,您应该会看到 "stateSave": true 。使用它,当页面刷新时,它会保存用户输入的参数搜索,但不会在 INPUT 字段中显示文本。

这就是我卡住的地方。

这是一个视觉表示:

刷新前 -

刷新后-

正如您在第二张图片中看到的那样,搜索适合以 TEST222 开头的 BOOKING,但文本在 BOOKING INPUT 字段中不再可见。

我确实遇到过这个帖子:https://datatables.net/reference/option/stateSaveCallback

但我不确定如何在我的代码中实现该代码。我什至不确定 stateSaveCallback 是否是正确的函数。

【问题讨论】:

    标签: javascript jquery datatables


    【解决方案1】:

    我终于找到了这个帖子:http://live.datatables.net/neqozaj/1/edit

    利用那篇文章,我能够将这段代码添加到整个函数中:

     var state = $dataTable.state.loaded();
     if ( state ) {
       $dataTable.columns().eq( 0 ).each( function ( colIdx ) {
       var colSearch = state.columns[colIdx].search;
    
       if ( colSearch.search ) {
         $('input', $('.filters th')[colIdx]).val( colSearch.search );
       }
      });
      $dataTable.draw();
     }
    

    使用这个,我能够达到我想要的效果。

    【讨论】:

      【解决方案2】:

      如果您有列级过滤器,请尝试以下代码。

      // Restore state, search and column level filter
          var state = table.state.loaded();
          if (state) {
              table.columns().eq(0).each(function (colIdx) {
                  var colSearch = state.columns[colIdx].search;
      
                  if (colSearch.search) {
                      $('input', table.column(colIdx).header()).val(colSearch.search);
                  }
              });
      
              table.draw();
          }
      
      
          // Apply the search
          table.columns().eq(0).each(function (colIdx) {
              $('input', table.column(colIdx).header()).on('keyup change', function () {
                  table
                      .column(colIdx)
                      .search(this.value)
                      .draw();
              });
          });
      

      【讨论】:

        猜你喜欢
        • 2015-12-04
        • 1970-01-01
        • 2016-12-08
        • 2017-03-05
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        相关资源
        最近更新 更多