首页 > 解决方案 > 如何结合自定义过滤器功能、自定义 selectSource 和动态表格填充?

问题描述

我正在尝试结合此答案中的方法来添加自定义过滤器选项,以使用动态填充的表格来选择空单元格。不幸的是,我发现在更新表格内容后,下拉列表中没有重新填充数据中的更新选项。

我在这里创建了一个示例来说明问题。最初,该表仅包含 3 行,第一列的过滤器下拉列表正确显示了这些选项,以及用于过滤到空行的“(空)”选项。

单击向表中添加更多数据的按钮后,“自定义”的过滤器下拉列表现在应该包含其他选项(“饼干”和“香肠”)以及之前存在的选项 - 例如“默认”列做。不幸的是,这并没有发生。

$(function(){

  $("#tblsort").tablesorter({
    theme: "default",
    widgets: ["filter"],

    widgetOptions: {
      filter_functions: {
        1: { '(Empty)': function(e, n, f, i, $r, c) { return $.trim(n) === ''; } }
      },
      filter_selectSource: {
        1: function(table, column, onlyAvail) {
            var array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
            array.unshift('(Empty)');
            return array;
        }
      }
    }
  });
  
  $("#addbtn").click(function(){
    // Pretend this is actually data loaded using AJAX or whatever
    $("#tblsort tbody").append("<tr><td>4</td><td>Biscuit</td><td>Biscuit</td></tr>");
    $("#tblsort tbody").append("<tr><td>5</td><td></td><td></td></tr>");
    $("#tblsort tbody").append("<tr><td>6</td><td>Sausages</td><td>Sausages</td></tr>");
    
    $("#tblsort").trigger("update", [true]);
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://mottie.github.io/tablesorter/dist/css/theme.default.min.css" rel="stylesheet"/>
<script src="https://mottie.github.io/tablesorter/dist/js/jquery.tablesorter.min.js"></script>
<script src="https://mottie.github.io/tablesorter/dist/js/jquery.tablesorter.widgets.min.js"></script>

<table id="tblsort">
<thead>
  <tr>
    <th class="filter-false">#</th>
    <th class="filter-select" data-placeholder="(All)">Custom</th>
    <th class="filter-select" data-placeholder="(All)">Default</th>
  <tr>
</thead>
<tbody>
  <tr><td>1</td><td>Foo</td><td>Foo</td></tr>
  <tr><td>2</td><td></td><td></td></tr>
  <tr><td>3</td><td>Bar</td><td>Bar</td></tr>
</tbody>
</table>

<button id="addbtn">Add more data</button>

这显然似乎是自定义过滤和添加新数据后更新表的调用之间的某种行为冲突。但我不能为我的生活找出如何解决它。

标签: filtertablesorter

解决方案


可能不是一个理想的解决方案 - 我有一段时间没有查看代码,所以我不记得更新选择的最佳方法 - 但这种方法有效:

$("#addbtn").click(function(){
  // Pretend this is actually data loaded using AJAX or whatever
  $("#tblsort tbody").append("<tr><td>4</td><td>Biscuit</td><td>Biscuit</td></tr>");
  $("#tblsort tbody").append("<tr><td>5</td><td></td><td></td></tr>");
  $("#tblsort tbody").append("<tr><td>6</td><td>Sausages</td><td>Sausages</td></tr>");

  $("#tblsort").trigger("update", [true]);
  $.tablesorter.filter.buildSelect( $("#tblsort"), 1, '', true, true);
});

我添加了一个buildSelect函数调用来强制重建。


推荐阅读