如何在JavaScript中嵌套调用函数?表格搜索函数调用故障排查
问题解决:抽离过滤函数后搜索失效的原因及修复方案
你的问题核心是变量作用域问题:filterSearch 函数无法直接访问 search 函数里定义的局部变量(比如 txtValue、filter、tr[i]、i),调用时这些变量在 filterSearch 里是未定义状态,自然不会生效。
修复方法很简单,把 filterSearch 需要用到的变量通过参数传递进去,让它不依赖外部作用域的变量:
步骤1:修改 filterSearch 函数,接收必要参数
将函数改为接收当前行元素、要匹配的文本、过滤关键词三个参数:
function filterSearch(row, text, keyword) { if (text.toUpperCase().indexOf(keyword) > -1) { row.style.display = ""; } else { row.style.display = "none"; } }
步骤2:在 search 函数里调用时传入对应参数
遍历表格行时,把当前的行元素、文本值、过滤关键词传进 filterSearch:
function search() { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("gvData"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[4]; if (td) { txtValue = td.textContent || td.innerText; // 传入需要的参数 filterSearch(tr[i], txtValue, filter); } } }
为什么这样改?
JavaScript里函数有独立的作用域,非嵌套的函数无法直接访问另一个函数的局部变量。通过参数传递,filterSearch 能拿到所有需要的数据,既解决了作用域问题,也让这个过滤函数更独立,后续其他场景需要类似逻辑时可以直接复用。
内容的提问来源于stack exchange,提问作者VX00
相关产品推荐
相关产品推荐

