如何实现点击按钮触发JS表格筛选函数 而非下拉框变更自动执行
实现方案
核心修改逻辑如下:
- 删除原代码中绑定在
.filter下拉框上的change事件监听,彻底取消下拉选值变更时的自动筛选行为 - 将筛选值收集、表格匹配的逻辑封装为全局可访问的
CalendarFilter函数,匹配按钮的点击触发需求 - 修正按钮的
onclick属性写法,原写法缺少函数调用括号,会导致点击无响应
第一步:修正按钮HTML写法
原按钮的onclick属性没有加执行括号,无法触发函数调用,修改为:
<button onclick="CalendarFilter()">Cercar</button>
第二步:替换原有JS代码
直接替换原有JS逻辑即可,修改后下拉框变更不会触发筛选,仅点击按钮时执行:
// 全局声明筛选函数,供按钮onclick直接调用 function CalendarFilter() { const selectedValues = []; // 遍历所有筛选下拉框收集选中值 $('.filter').each(function () { const colIndex = $(this).data('col'); $(this).find('option:selected').each(function () { if ($(this).val() !== "") { selectedValues.push({ text: $(this).text(), colId: colIndex }); } }); }); // 执行表格行筛选 renderTableFilter('table > tbody > tr', selectedValues); } // 表格筛选渲染逻辑 function renderTableFilter(selector, filterValues) { $(selector).each(function () { const $row = $(this); const cellTexts = $row.text().trim().split('\n'); const cellMatchStatus = []; for (let i = 0; i < cellTexts.length; i++) { cellMatchStatus[i] = { text: cellTexts[i].trim(), matched: false }; } // 逐列匹配筛选值 $.each(filterValues, function (_, filterItem) { const matchReg = new RegExp("\\b" + filterItem.text + "\\b"); if (cellMatchStatus[filterItem.colId].text.search(matchReg) >= 0) { cellMatchStatus[filterItem.colId].matched = true; } }); // 所有筛选条件都匹配才显示行 const matchedCount = cellMatchStatus.filter(item => item.matched).length; const shouldShow = matchedCount === filterValues.length; shouldShow ? $row.show() : $row.hide(); }); } $(document).ready(function () { // 此处可加页面初始化逻辑,比如默认展示全部表格行: // $('table > tbody > tr').show(); // 原$('.filter').change事件监听已完全移除,不会自动触发筛选 });
可选扩展
如果需要加重置筛选按钮,绑定如下逻辑即可:
function resetFilter() { $('.filter').val(''); // 清空所有下拉框选中值 $('table > tbody > tr').show(); // 展示所有表格行 }
内容的提问来源于stack exchange,提问作者mdomfu
相关产品推荐
相关产品推荐

