如何仅用JavaScript实现搜索无结果时显示“未找到结果”提示
解决方案
你可以通过动态创建提示元素的方式实现需求,无需修改HTML代码。以下是修改后的JavaScript代码:
function myFunction() { const userInput = document.getElementById("myInput").value.toUpperCase(); const tableRows = document.querySelectorAll("table tr"); let matchCount = 0; // 移除已存在的提示行,避免重复添加 const existingNoResult = document.getElementById("no-result-row"); if (existingNoResult) { existingNoResult.remove(); } for (let i = 0; i < tableRows.length; i++) { const row = tableRows[i]; const rowTextContent = row.innerText.toUpperCase(); const isMatch = rowTextContent.includes(userInput); row.style.display = isMatch ? "" : "none"; // 统计匹配的数据行(仅包含<td>的行,排除表头行) if (isMatch && row.querySelector("td")) { matchCount++; } } // 当用户输入非空且无匹配数据行时,添加提示 if (matchCount === 0 && userInput.trim() !== "") { const table = document.getElementById("myTable"); const noResultRow = document.createElement("tr"); noResultRow.id = "no-result-row"; const noResultCell = document.createElement("td"); noResultCell.colSpan = "3"; noResultCell.textContent = "未找到结果"; // 匹配表格样式 noResultCell.style.textAlign = "center"; noResultCell.style.padding = "8px 10px"; noResultCell.style.backgroundColor = "#D3D3D3"; noResultRow.appendChild(noResultCell); table.appendChild(noResultRow); } }
关键逻辑说明:
- 移除旧提示:每次执行搜索前,先检查并移除之前创建的提示行,防止重复渲染
- 统计匹配行:遍历表格行时,仅统计包含
<td>的数据行(排除表头行)的匹配数量 - 动态创建提示:当无匹配数据且用户输入非空时,创建一个跨列的表格行,插入到表格末尾,并设置与现有表格一致的样式
- 空输入处理:当用户清空搜索框时,自动隐藏提示并恢复显示所有行
内容的提问来源于stack exchange,提问作者magicsinger
相关产品推荐
相关产品推荐

