如何基于<tr>数据属性实现DataTables自定义下拉筛选?
实现DataTables行级data属性组合筛选
要实现基于<tr>行级data属性的多条件组合筛选,核心是利用DataTables的自定义搜索扩展($.fn.dataTable.ext.search),通过监听下拉框变化触发表格重绘,在自定义搜索逻辑中校验行的属性是否匹配筛选条件。
完整实现代码
HTML部分(保持原结构不变)
<select id="custom-select-filter-1"> <option value="">Please select filter 1...</option> <option value="one">One</option> <option value="two">Two</option> <option value="three">Three</option> </select> <select id="custom-select-filter-2"> <option value="">Please select filter 2...</option> <option value="four">Four</option> <option value="five">Five</option> <option value="six">Six</option> </select> <table id="example"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Category</th> </tr> </thead> <tbody> <tr data-testattribute1="one" data-testattribute2="four"> <td>1</td> <td>Apples</td> <td>Fruit</td> </tr> <tr data-testattribute1="two" data-testattribute2="five"> <td>2</td> <td>Oranges</td> <td>Fruit</td> </tr> <tr data-testattribute1="three" data-testattribute2="six"> <td>3</td> <td>Lexus</td> <td>Cars</td> </tr> <tr data-testattribute1="one" data-testattribute2="five"> <td>4</td> <td>Winchester</td> <td>Guns</td> </tr> </tbody> </table>
JavaScript部分(修改后)
$(document).ready(function(){ // 初始化DataTable const table = $('#example').DataTable({ order: [[1, 'asc']] }); // 添加自定义搜索过滤器 $.fn.dataTable.ext.search.push( function(settings, data, dataIndex) { // 获取当前两个筛选器的选中值 const filter1Val = $('#custom-select-filter-1').val(); const filter2Val = $('#custom-select-filter-2').val(); // 获取当前行的DOM节点,提取行级data属性 const row = table.row(dataIndex).node(); const rowAttr1 = $(row).data('testattribute1'); const rowAttr2 = $(row).data('testattribute2'); // 筛选逻辑:空值筛选器不生效,非空则必须匹配对应属性 const matchesFilter1 = filter1Val === '' || rowAttr1 === filter1Val; const matchesFilter2 = filter2Val === '' || rowAttr2 === filter2Val; // 两个条件同时满足才显示该行 return matchesFilter1 && matchesFilter2; } ); // 监听两个下拉框的变化,触发表格重绘(自动执行自定义筛选) $('#custom-select-filter-1, #custom-select-filter-2').on('change', function(){ table.draw(); }); });
关键逻辑说明
- 自定义搜索扩展:
$.fn.dataTable.ext.search是DataTables提供的全局搜索钩子,每次表格重绘时会遍历每一行,返回true则显示该行,false则隐藏。 - 行属性获取:通过
table.row(dataIndex).node()获取当前行的DOM元素,再用jQuery的data()方法提取行的data-testattribute1和data-testattribute2值。 - 组合筛选逻辑:
- 若筛选器值为空(默认选项),则该筛选条件不生效;
- 若筛选器有选中值,则必须匹配对应行的属性;
- 只有同时满足两个筛选器的条件,该行才会被显示。
- 触发筛选:下拉框变化时调用
table.draw(),触发表格重绘,自动执行自定义筛选逻辑。
内容的提问来源于stack exchange,提问作者Pegues
相关产品推荐
相关产品推荐

