首页 > 解决方案 > 当 tablesorter 表显示最后一行时触发显示隐藏的 div

问题描述

本质上,我找不到如何确定我的 TS 表是否显示最后一个可用行。当A)表格显示所有可用项目(不再有可访问的页面)或B)当用户移动到表格的最后一页时,我需要能够在表格下方显示“添加客户端”按钮/ div .

这可以用 Mottie 的 tablesorter 完成吗?

这是我加载表格排序器的 javascript..

function loadTSTable(table2load){
    
  /* <table id="tableX"> tag to specify different tables to be threated by the Tablesorter */

  var $table1 = $('#' + table2load); 

  /***************************
   * main tablesorter config
   ***************************/
  $table1.tablesorter( {
  theme : "bootstrap",

  widthFixed: true,

  /* click on column header a 3rd time to disable sorting, else need to ctrl+click */
  sortReset: false,


  // widget code contained in the jquery.tablesorter.widgets.js file
  // use the zebra stripe widget if you plan on hiding any rows (filter widget)
  // the uitheme widget is NOT REQUIRED!
  // PROY: eventually also look at the Output Widget
  widgets : [ "filter", "columnSelector", "columns", "zebra", "mark"],

  widgetOptions : {
    // using the default zebra striping class name, so it actually isn't included in the theme variable above
    // this is ONLY needed for bootstrap theming if you are using the filter widget, because rows are hidden
    zebra : ["even", "odd"],

    // class names added to columns (need 'columns' widget) when sorted
    columns: [ "primary", "secondary", "tertiary" ],

    /* -------------------------
     * FILTER WIDGET OPTIONS
     * -------------------------*/

    // class added to filtered rows (rows that are not showing); needed by pager plugin
    // proy is this needed !?
    filter_filteredRow   : 'filtered',

    // reset filter button
    filter_reset : ".reset",

    // auto-hide filter row, popup when moused-over
    filter_hideFilters: false,

    // GLOBAL SEARCH FACILITY
    // filter_anyMatch replaced! Instead use the filter_external option
    // Set to use a jQuery selector (or jQuery object) pointing to the
    // external filter (column specific or any match)
    filter_external : '.search',

    // add a default column filter type "~{query}" to make fuzzy searches default to the first name column
    //filter_defaultFilter: { 1 : '~{query}' },
    filter_defaultFilter: {},

    // include column filters
    filter_columnFilters: true,

    // save filter data, even if page is reloaded, they will still be there!
    filter_saveFilters : false,

    // ignore case in search
    filter_ignoreCase: true,

    // extra css class name (string or array) added to the filter element (input or select)
    //filter_cssFilter: "form-control form-control-sm p-1",

    // OR, to set specific css to specific columns:
      filter_cssFilter: [
        'form-control form-control-sm p-1',
        'form-control form-control-sm p-1',
        'form-control form-control-sm p-1',
        'form-control form-control-sm p-1'        
      ],

      // Add select box to columns (zero-based index)
      // each option has an associated function that returns a boolean
      // function variables:
      // e = exact text from cell
      // n = normalized value returned by the column parser
      // f = search filter input value
      // i = column index (zero-based index)
      filter_functions : {
      },

     /* -------------------------
      * MARK WIDGET OPTIONS
      * see: https://mottie.github.io/tablesorter/docs/example-widget-mark.html
      * -------------------------*/      
  
     // *** mark widget only settings
      mark_tsUpdate : 'markUpdate',
      mark_tsIgnore : {
        // don't highlight 'artistic' and 'status' columns
        //4: true,
        //6: true,
      },
      // *** default settings for non-regular expression searches only
      mark_accuracy: 'partially',
      mark_caseSensitive: false,
      mark_diacritics: true,
      mark_separateWordSearch: true,
      mark_synonyms: {},
    
      // *** settings that apply to regex & non-regular expression searches
      mark_acrossElements: false,
      mark_className: '',
      mark_debug: false,
      mark_element: 'mark',
      mark_exclude: [],
      mark_iframes: false,
      mark_log: console,
    
      // callback functions
      mark_done: function(totalMatches) {},
      mark_each: function(element) {},
      mark_filter: function(node, term, totalMatches, matches) {
        // "matches" parameter is not defined for regular expression searches
        return true;
      },
      mark_noMatch: function(termNotFound) {},
    }
  });

  /***************************
   * setup Pager
   ***************************/
  $table1.tablesorterPager({
  // target the pager markup - see the HTML block below
  container: $(".ts-pager-" + table2load),

  // target the pager page select dropdown - choose a page
  cssGoto  : ".pagenum-" + table2load,
  
  // target the page size selector
  cssPageSize: '.pagesize-' + table2load,

  // remove rows from the table to speed up the sort of large tables.
  // setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled.
  removeRows: false,

  // output string - default is '{page}/{totalPages}';
  // possible variables: {page}, {totalPages}, {filteredPages}, {startRow}, {endRow}, {filteredRows} and {totalRows}
  output: '{startRow} - {endRow} / {filteredRows} ({totalRows})'

  });

  /***************************
   * show error message if no data
   ***************************/
  $table1.on('filterEnd filterReset pagerComplete', function(e, table){
      var fr, table = this;
      if (table.config.pager) {
          $.tablesorter.showError(table); // remove all prior error rows from the table thead, if any
          fr = table.config.pager.filteredRows;
          if (fr === 0) {
          
            if(table2load == 'tblAllProducers'){
              msg = "No clients were found in this list.\nYou can request to add a new client below.";
              $('#addClient').addClass('d-block'); // show 'Add Client' button
            }
            else {              
              msg = "No clients were found in this list. Try searching in all clients.";
            }
          
            $.tablesorter.showError(table, msg);
            
            // hotfix: since error messages are placed in thead, force a different font-size then what defaults in thead for text-size! 
            $('.tablesorter-errorRow').css("font-size", "large");            
          }
      }
  });

}

干杯! 拍

编辑:所以,部分修复:

  if (fr === 0) {
    ...
  }
  // show 'Add Client' button if we're on last page          
  else {
    // page variable is zero-indexed current page number;  totalPages is well, total pages! 
    if( (table.config.pager.totalPages - table.config.pager.page ) === 1)  {
      $('#addClient').addClass('d-block'); // show 'Add Client' button
    }
  }

新编辑:尝试实现'tablesorter-initialized'方法,我还尝试使用以下方法使表格显示DIV,如果它在表格加载时的最后一页上:

$table1.tablesorter( {

  // if we're already showing last page, show 'Add Client' button
  initialized : function(table) {
    console.warn(table.config.pager); // shows me 'undefined'
    console.warn(table.config); // shows me all config properties, and 'pager' IS in them!!?

    if( (table.config.pager.totalPages - table.config.pager.page ) === 1)  {
      $('#addClient').addClass('d-block'); // show 'Add Client' button
    }  
  },

  ...
});

它不起作用。由于某些原因,table.config.pager将是undefined,但是table.config的输出似乎确实具有 pager 属性!见图片:

在此处输入图像描述

我在这里有点困惑:(

编辑 3:pagerInitialized 事件仍然不行。这是我的代码:

  $table1.on('filterEnd filterReset pagerComplete pagerInitialized', function(e, table){
      
      var fr, table = this;
      
      if (table.config.pager) {
          $.tablesorter.showError(table); // remove all prior error rows from the table thead, if any
          fr = table.config.pager.filteredRows;
          
          if (fr === 0) {
          
            if(table2load == 'tblAllProducers'){
              msg = localejs.gettext("No clients were found in this list.\nYou can request to add a new client below.");
              $('#addClient').addClass('d-block'); // show 'Add Client' button if we've found no match through filter
            }
            else {              
              msg = localejs.gettext("No clients were found in this list. Try searching in all clients.");
            }
          
            $.tablesorter.showError(table, msg);                       
          }
          
          // show 'Add Client' button if we're on last page          
          else {
            // page variable is zero-indexed current page number;  totalPages is well, total pages! 
            if( (table.config.pager.totalPages - table.config.pager.page ) === 1)  {
              $('#addClient').addClass('d-block'); // show 'Add Client' button
            }
          }
      }
  });

编辑 4:解决方案

$table1.bind('pagerInitialized', function(event, options) {
  // page variable is zero-indexed current page number
  if( (options.totalPages - options.page ) == 1)  {
    $('#addClient').addClass('d-block'); // show 'Add Client' button
  }
});


$table1.tablesorter(...);

标签: jquerytablesorter

解决方案


推荐阅读