JavaScript中自动填充输入值清空时如何删除所有匹配失效的表格行
问题修复方案
核心原因
你的代码存在两个问题导致旧数据残留:
- 每次输出搜索匹配结果前没有清空表格已有内容,新数据会不断追加到旧数据下方
- 输入内容清空时仅删除了第一行,没有移除所有历史匹配行
修复步骤
1. 新增表格清空公共方法
优先用直接清空tbody内容的方式,比循环删除行更简单高效:
const clearTable = () => { const tableBody = document.getElementById("list").getElementsByTagName('tbody')[0]; tableBody.innerHTML = ''; }
2. 修改outputHtml方法,每次渲染前先清空旧数据
同时修复你原有代码里全局formData导致的行数据覆盖问题:
const outputHtml = matches => { // 每次渲染前先清空旧表格内容 clearTable(); if (matches.length > 0) { matches.forEach(matched => { // 每次循环新建formData对象,不要用全局对象避免数据覆盖 const formData = {}; formData["id_number"] = matched.id formData["first_name"] = matched.firstName formData["last_name"] = matched.lastName formData["email"] = matched.email formData["department"] = matched.department formData["location"] = matched.location insertNewRecord(formData) }) } }
3. 删除searchStates中冗余的删行逻辑
现在已经不需要单独处理输入为空的清空逻辑了,直接删掉对应的代码块即可:
const searchStates = async searchText => { const res = await fetch("companydirectory/libs/php/getAll.php") const states = await res.json() let matches = states.data.filter(state => { const regex = new RegExp(`^${searchText}`, "gi") return state.id.match(regex) }) // 以下代码块直接删除即可 // if (searchText.length === 0) { // matches = [] // document.getElementById('id_data').deleteRow(0); // } outputHtml(matches) }
可选优化
如果你的表格tbody默认有「暂无数据」之类的固定提示行,可以在clearTable方法中加判断保留提示行,避免清空后无提示:
const clearTable = () => { const tableBody = document.getElementById("list").getElementsByTagName('tbody')[0]; // 保留第一行提示,删除其他行 while(tableBody.rows.length > 1) { tableBody.deleteRow(1); } }
内容的提问来源于stack exchange,提问作者Coder_k
相关产品推荐
相关产品推荐

