如何为现有PHP渲染的jQuery表格添加每列独立过滤搜索功能?
表格列独立搜索实现方案
核心改造点
- 给每个表头单元格内嵌对应列的独立搜索输入框,通过自定义属性标记输入框对应的列索引
- 调整原有过滤逻辑:单行需要同时满足「所有已填写的列搜索条件」+「原有全局搜索条件」才会展示
- 补充正则特殊字符转义逻辑,避免用户输入
*、(、.等特殊字符时脚本报错
改造后的完整代码
表格结构部分
原有的全局搜索框、PHP数据渲染逻辑完全保留,仅修改表头结构嵌入列搜索输入框:
<div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Quick Search</span> </div> <input id="filterContent" class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search"> </div> <table class="table table-striped table-bordered table-sm text-center" style="width:100%; margin:auto;"> <thead class="text-center table-info"> <tr> <th> # <input type="text" class="form-control form-control-sm mt-1 column-filter" data-column-index="0" placeholder="过滤"> </th> <th> Customer <input type="text" class="form-control form-control-sm mt-1 column-filter" data-column-index="1" placeholder="过滤"> </th> <th> Phone 1 <input type="text" class="form-control form-control-sm mt-1 column-filter" data-column-index="2" placeholder="过滤"> </th> <th> Phone 2 <input type="text" class="form-control form-control-sm mt-1 column-filter" data-column-index="3" placeholder="过滤"> </th> </tr> </thead> <tbody class="quickSearch"> <?php foreach($users as $user): $counter++ ?> <tr class="text-center"> <td><?= $counter; ?></td> <td><?= $user['CUSTOMER'] ;?></td> <td><?= $user['PHONE_1'] ;?></td> <td><?= $user['PHONE_2'] ;?></td> </tr> <?php endforeach; ?> </tbody> </table>
过滤脚本部分
替换原有过滤逻辑,实现全局搜索、列搜索的组合匹配,避免逻辑互相覆盖:
<script type="text/javascript"> $(document).ready(function () { // 正则特殊字符转义工具,避免输入特殊字符触发语法错误 function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } // 统一的行过滤触发函数,所有搜索框输入变化时统一调用 function applyFilter() { // 读取全局搜索值,生成匹配规则 const globalSearchVal = escapeRegExp($('#filterContent').val().trim()); const globalReg = new RegExp(globalSearchVal, 'i'); // 按列索引收集所有列的搜索规则 const columnFilters = []; $('.column-filter').each(function() { const colIndex = $(this).data('column-index'); const filterVal = escapeRegExp($(this).val().trim()); columnFilters[colIndex] = new RegExp(filterVal, 'i'); }); // 逐行匹配规则 $('.quickSearch tr').each(function() { const $row = $(this); let isMatch = true; // 先校验全局搜索规则 if (!globalReg.test($row.text())) { isMatch = false; } // 逐列校验对应列的搜索规则 if (isMatch) { $row.children('td').each(function(colIndex) { const cellReg = columnFilters[colIndex]; // 跳过未填写过滤值的列 if (cellReg && !cellReg.test($(this).text().trim())) { isMatch = false; return false; // 匹配失败直接跳出当前行的列遍历 } }); } // 根据匹配结果控制行的展示状态 $row.toggle(isMatch); }); } // 绑定全局搜索输入事件 $('#filterContent').keyup(applyFilter); // 绑定所有列搜索的输入事件 $('.column-filter').keyup(applyFilter); }); </script>
功能说明
- 列搜索为与逻辑匹配:多列同时输入过滤值时,只有同时满足所有列条件的行才会展示,比如客户名列输入“张”、手机号列输入“138”,仅展示客户名含“张”且手机号含“138”的行
- 原有全局搜索功能不受影响,可和列搜索叠加生效
- 列输入框已做尺寸适配,不会撑大表头高度,兼容特殊输入字符
内容的提问来源于stack exchange,提问作者Guillermo Rubio
相关产品推荐
相关产品推荐

