You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于JavaScript二维数组实现带列搜索的DataTables初始化

实现带列单独搜索功能的DataTables表格

直接把你的dataSet和headers整合到带搜索功能的代码中即可,以下是完整可运行的代码:

const dataSet = [['a','b','x'],['c','d','y'],['e','f','z']];
const headers = [{'title':'A'},{'title': 'B'},{'title': 'C'}]

$(document).ready(function () {
    // 克隆表头并添加筛选行
    $('#example thead tr')
        .clone(true)
        .addClass('filters')
        .appendTo('#example thead');
 
    var table = $('#example').DataTable({
        data: dataSet, // 引入你的数据源
        columns: headers, // 引入你的表头配置
        orderCellsTop: true,
        fixedHeader: true,
        initComplete: function () {
            var api = this.api();
 
            // 为每一列添加筛选输入框
            api
                .columns()
                .eq(0)
                .each(function (colIdx) {
                    var cell = $('.filters th').eq(
                        $(api.column(colIdx).header()).index()
                    );
                    var title = $(cell).text();
                    $(cell).html('<input type="text" placeholder="' + title + '" />');
 
                    // 绑定筛选输入框的事件
                    $(
                        'input',
                        $('.filters th').eq($(api.column(colIdx).header()).index())
                    )
                        .off('keyup change')
                        .on('change', function (e) {
                            $(this).attr('title', $(this).val());
                            var regexr = '({search})';
 
                            var cursorPosition = this.selectionStart;
                            api
                                .column(colIdx)
                                .search(
                                    this.value != ''
                                        ? regexr.replace('{search}', '(((' + this.value + ')))')
                                        : '',
                                    this.value != '',
                                    this.value == ''
                                )
                                .draw();
                        })
                        .on('keyup', function (e) {
                            e.stopPropagation();
 
                            $(this).trigger('change');
                            $(this)
                                .focus()[0]
                                .setSelectionRange(cursorPosition, cursorPosition);
                        });
                });
        },
    });
});

关键说明

  • 你的dataSet和headers直接作为配置项传入DataTables初始化参数,和基础用法完全兼容
  • 表头克隆逻辑会自动读取headers中的title文本,生成对应提示文字的筛选输入框
  • 列搜索的核心逻辑无需修改,会自动适配你定义的列数量和结构

内容的提问来源于stack exchange,提问作者aku

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:32:34