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

jQuery Datatables如何仅为指定列添加表头搜索筛选框

Datatables指定列添加表头搜索框实现方案

你现有代码会遍历所有列生成搜索框,只需要加一层索引过滤逻辑即可,具体修改如下:

// 原有克隆筛选行的逻辑不变
$('#OBTable thead tr')
  .clone(true)
  .addClass('filters')
  .appendTo('#OBTable thead');

var table = $('#OBTable').dataTable({
  "ajax": {
    "url": "SelectData.php",
    "dataSrc": "data",
  },
  orderCellsTop: true,
  select: true,
  initComplete: function () {
    var api = this.api();
    // 定义需要添加搜索框的列索引,从0开始计数
    const enableSearchCols = [0, 6];

    api
      .columns()
      .eq(0)
      .each(function (colIdx) {
        var cell = $('.filters th').eq(
          $(api.column(colIdx).header()).index()
        );
        // 新增判断:当前列不在允许搜索的列表里,清空单元格内容直接跳过
        if (!enableSearchCols.includes(colIdx)) {
          $(cell).empty();
          return;
        }
        // 原有生成输入框和绑定事件的逻辑不变
        var title = $(cell).text();
        $(cell).html('<input type="text" placeholder="' + title + '" />');

        $('input', $('.filters th').eq($(api.column(colIdx).header()).index()))
          .off('keyup change')
          .on('keyup change', function (e) {
            e.stopPropagation();
            $(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();
            $(this)
              .focus()[0]
              .setSelectionRange(cursorPosition, cursorPosition);
          });
      });
  },
});

如果后续需要调整开放搜索的列,直接修改enableSearchCols数组里的索引值即可,注意Datatables的列索引是从0开始从左到右计数的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:15:03