簡體   English   中英

刷新后jQuery數據表保留過濾器參數

[英]jQuery datatable retain filter parameter after refresh

根據我之前的一些問題,我正在使用數據表。 我能夠在表的頂部添加 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 是否是正確使用的函數。

我終於找到了這篇文章: 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();
 }

使用這個,我能夠達到我想要的效果。

如果您有列級過濾器,請嘗試以下代碼。

// 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();
        });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM