首页 > 解决方案 > 防止 DataTables 自定义过滤器影响页面上的所有表

问题描述

当我们向 DataTables 添加自定义过滤器时:

$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
  ...
})

它在一张桌子上按预期工作。但是,如果我们在同一页面上有多个表,则所有过滤器都会影响所有表。如何创建仅影响特定表的自定义过滤器?

标签: datatablesfiltering

解决方案


所有自定义过滤器都可以全局工作,因为$.fn.dataTable.ext.search页面上的任何 DataTable 在重绘时都会考虑到全局数组。没有办法绕过它,这就是DT的设计方式。

但是,通过使用 DT 的插件架构并简单地挂钩相关事件,可以很容易地在需要时将全局数组替换为本地自定义过滤器(如果有):

$.fn.dataTable.Api.register('filter.push', function(fn, draw) {
  if (!this.__customFilters) {
    var filters = this.__customFilters = [] 
    this.on('mousedown preDraw.dt', function() {
      $.fn.dataTable.ext.search = filters
    })
  }
  this.__customFilters.push(fn)
  $.fn.dataTable.ext.search = this.__customFilters 
  this.draw()
})

$.fn.dataTable.Api.register('filter.pop', function() {
  if (!this.__customFilters) return
  this.__customFilters.pop()
})

而已。现在,如果您有一个包含多个数据表的页面,并且您希望自定义过滤器仅适用于一个特定的表:

table.filter.push(function(settings, data, dataIndex) {
  ...
})

如果要删除过滤器table.filter.pop()

这是一个在同一页面上包含三个表的演示,每个表都实现了自己的自定义过滤器-> http://jsfiddle.net/gc4ow8yr/


推荐阅读