gpt4 book ai didi

datatables - 防止 DataTables 自定义过滤器影响页面上的所有表

转载 作者:行者123 更新时间:2023-12-04 16:29:09 26 4
gpt4 key购买 nike

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

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

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

最佳答案

所有自定义过滤器都可以在全局范围内使用,因为 $.fn.dataTable.ext.search是一个全局数组,页面上的任何 DataTable 在重绘时都会考虑在内。没有办法解决它,这只是 DT 的设计方式。

但是,通过使用 DT 的插件架构并简单地 Hook 到相关事件,很容易在需要时用本地自定义过滤器替换全局数组,如果有的话:

$.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/

关于datatables - 防止 DataTables 自定义过滤器影响页面上的所有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55242822/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com