datatables - 防止 DataTables 自定义过滤器影响页面上的所有表
问题描述
当我们向 DataTables 添加自定义过滤器时:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
...
})
它在一张桌子上按预期工作。但是,如果我们在同一页面上有多个表,则所有过滤器都会影响所有表。如何创建仅影响特定表的自定义过滤器?
解决方案
所有自定义过滤器都可以全局工作,因为$.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/
推荐阅读
- php - 在 bitmex API 中更改 SYMBOL CONST
- sql - 使用 JSON1 跨多个表聚合 SQLite 查询
- node.js - 错误 TS2322:类型“任何”不可分配给类型“从不”
- python - 插入表并得到错误: sqlite3.ProgrammingError: You did not provide a value for binding 1
- python - Tkinter - 要求用户输入整数,直到他们在 tkinter 输入框中给出有效响应
- vue.js - 如何解决已分配计算属性但在 vue api 组合中没有设置器的问题?
- codenameone - Codenameone: start() 方法并不总是在应用程序恢复时调用
- vb6 - 变量未定义
- java - 集成测试期间对象中的 ArrayLIst 未更新
- java - 从 Java 中的浮点值接收与 php 中相同的 sha256 的问题