防止 DataTables 自定义过滤器影响页面上的所有表 [英] Prevent DataTables custom filter from affecting all tables on a page
问题描述
当我们向 DataTables 添加自定义过滤器时:
When we add a custom filter to DataTables:
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
...
})
它在一张桌子上按预期工作.但是,如果我们在同一页面上有多个表,则所有过滤器都会影响所有表.如何创建仅影响特定表的自定义过滤器?
it works as expected on one table. However, if we have multiple tables on the same page, all filters affects all tables. How to create custom filters that only affect a specific table?
推荐答案
所有自定义过滤器都在全局范围内工作,因为 $.fn.dataTable.ext.search
是一个全局数组,页面上的任何 DataTable 都会用到重绘时的考虑.没有办法解决它,这只是 DT 的设计方式.
All custom filters works globally because $.fn.dataTable.ext.search
is a global array any DataTable on a page takes into consideration when they are redrawn. There is no way around it, it is simply how DT is designed.
但是,通过使用 DT 的插件架构并简单地挂钩到相关事件,很容易在需要时将全局数组替换为本地自定义过滤器(如果有):
However, by using DT's plug-in architecture and simply hook into the relevant events, it is easy to replace the global array with local custom filters when needed, if any :
$.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()
})
就是这样.现在,如果您有一个包含多个数据表的页面,并且您希望自定义过滤器仅适用于一个特定的表:
Thats it. Now, if you have a page with multiple DataTables, and you want a custom filter to work for one specific table only :
table.filter.push(function(settings, data, dataIndex) {
...
})
如果要删除过滤器table.filter.pop()
这是一个演示,在同一页面上有三个表,每个表都实现了自己的自定义过滤器 -> http://jsfiddle.net/gc4ow8yr/
Here is a demo with three tables on the same page, each of them having their own custom filter implemented -> http://jsfiddle.net/gc4ow8yr/
这篇关于防止 DataTables 自定义过滤器影响页面上的所有表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!