Datatables表头搜索列实现精确匹配的代码修改问题
实现方案
要实现Datatables列搜索的精确匹配,只需对现有代码的搜索逻辑做3处调整:
- 新增正则特殊字符转义逻辑,避免用户输入的特殊字符(如
.、*)触发意外正则匹配 - 给搜索关键词加正则首尾定界符
^和$,强制匹配单元格完整内容 - 修正Datatables
search()方法的参数配置,启用正则匹配、关闭默认智能搜索
修改后的完整代码
$('#OBTable thead tr') .clone(true) .addClass('filters') .appendTo('#OBTable thead'); $('#OBTable thead tr:eq(1) th').text(""); var table = $('#OBTable').dataTable({ "ajax": { "url": "SelectData.php", "dataSrc": "data", }, orderCellsTop: true, select: true, initComplete: function () { var api = this.api(); // 新增:正则特殊字符转义函数 function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } // For each column api .columns([0,6]) .eq(0) .each(function (colIdx) { // Set the header cell to contain the input element var cell = $('.filters th').eq( $(api.column(colIdx).header()).index() ); var title = $(cell).text(); $(cell).html('<input type="search" class="form-control form-control-sm" placeholder="Filter.." />'); // On every keypress in this input $( 'input', $('.filters th').eq($(api.column(colIdx).header()).index()) ) .off('keyup change') .on('keyup change', function (e) { e.stopPropagation(); // Get the search value $(this).attr('title', $(this).val()); var searchVal = $(this).val().trim(); var cursorPosition = this.selectionStart; // Search the column for that value api .column(colIdx) .search( searchVal != '' ? '^' + escapeRegExp(searchVal) + '$' // 用^$包裹转义后的搜索值 : '', searchVal != '', // 第二个参数设为true,启用正则匹配 false // 第三个参数设为false,关闭Datatables默认智能搜索 ) .draw(); $(this) .focus()[0] .setSelectionRange(cursorPosition, cursorPosition); }); }); }, });
效果验证
修改后即可实现需求:
- 输入
Anneke时只会返回单元格内容完全等于Anneke的行,不会匹配到Janneke - 输入
4时只会返回单元格内容完全等于4的行,不会匹配到14、24等包含4的内容
内容的提问来源于stack exchange,提问作者Martin4523
相关产品推荐
相关产品推荐

