DataTables回调函数中this.api操作多表格下拉筛选仅首个表格生效问题
问题根因
你的代码存在两处核心错误,导致第二个表格无法正常渲染筛选下拉框:
initComplete是单表格实例初始化完成的专属回调,触发时回调内this.api()返回的就是当前正在初始化的表格API实例,不需要额外调用tables(索引)跨实例选表。你在初始化table2时调用tables([1]),此时table2还未完成全局注册,索引1不存在,无法匹配到目标列。- 下拉框挂载时用的
$('thead tr:eq(1) th:eq(...)')是全局选择器,会永远匹配页面中第一个表格的表头单元格,哪怕逻辑在table2的初始化流程里,也会把下拉框插到第一个表格中。
修正方法
- 删除
initComplete内多余的tables([索引])调用,直接在当前表格API实例上调用columns()指定需要加筛选的列即可 - 所有DOM操作都限定在当前表格范围内,禁止使用全局选择器,避免跨表格干扰
修正后完整代码
$('#table1').DataTable({ "dom": '<"dtWrapper"<f>lrti<"paginate0rem"p>>', drawCallback: function(){ if (feather) { feather.replace({ width: 14, height: 14 }); } }, orderCellsTop: true, initComplete: function () { // 直接取当前表格API,不需要跨表选索引 const api = this.api(); // 限定查找范围为当前表格 const $thead = $(api.table().header()).closest('thead'); api.columns([3, 4]).every( function () { let column = this, select = $('<select class="form-control"><option value=""></option></select>') // 仅在当前表格的表头找对应列的单元格 .appendTo($thead.find('tr:eq(1) th:eq(' + this.index() + ')')) .on('change', function () { let val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false) .draw(); }); column.data().unique().sort().each(function (d, j) { select.append('<option value="'+d+'">'+d+'</option>') }); }); } }); $('#table2').DataTable({ "dom": '<"dtWrapper"<f>lrti<"paginate0rem"p>>', drawCallback: function(){ if (feather) { feather.replace({ width: 14, height: 14 }); } }, orderCellsTop: true, initComplete: function () { // 直接取当前表格API const api = this.api(); // 限定查找范围为当前表格 const $thead = $(api.table().header()).closest('thead'); api.columns([2, 3]).every( function () { let column = this, select = $('<select class="form-control"><option value=""></option></select>') // 仅在当前表格的表头挂载下拉框 .appendTo($thead.find('tr:eq(1) th:eq(' + this.index() + ')')) .on('change', function () { let val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false) .draw(); }); column.data().unique().sort().each(function (d, j) { select.append('<option value="'+d+'">'+d+'</option>') }); }); } });
注意:使用该写法需要保证两个表格的表头都有2行
tr(即提前配置好带筛选行的双层表头结构),否则tr:eq(1)会找不到对应行。
内容的提问来源于stack exchange,提问作者Jolan
相关产品推荐
相关产品推荐

