JavaScript关键词匹配搜索框输入匹配词无结果展示问题排查
问题根因
核心问题出在关键词匹配的循环逻辑错误:
- 遍历关键词数组时,每一次对比都会直接修改结果框的display状态,即使前面已经匹配到了正确的关键词,后续不匹配的关键词也会把display重新覆盖为
none - 只有当输入的内容刚好匹配数组的最后一个关键词
Naehrstoffe时,最终才会保持显示状态,其他所有匹配的情况都会被后续的不匹配逻辑隐藏 - 补充:当前监听的
search事件仅在按下回车、点击输入框清空按钮时触发,如果需要输入过程中实时响应,可以额外绑定input事件
修复方案
修改JavaScript逻辑如下:
var wordsHarmi = [ "Bodenhilfsstoff", "Dünger","Duenger", "Harmi", "Soil", "Harmi-Soil", "Boden", "Mineralien", "Wurzelwachstum", "Nährstoffe", "Naehrstoffe", ] let harmiSuche = document.getElementById('harmi-suche') const inputSearch = document.getElementById('input-suche'); // 同时绑定search和input事件,同时支持回车触发和实时搜索 ['search', 'input'].forEach(evt => { inputSearch.addEventListener(evt, (event) => { // 先去掉输入前后的空白字符再转小写 const searchString = event.target.value.trim().toLowerCase(); let isMatch = false; // 遍历数组查找匹配项 for (let index = 0; index < wordsHarmi.length; index++) { if (wordsHarmi[index].toLowerCase() === searchString) { isMatch = true; // 匹配到就跳出循环,不需要继续遍历 break; } } // 遍历结束后统一设置显示状态 if (isMatch) { console.log("Word found"); harmiSuche.style.display = 'flex'; } else { harmiSuche.style.display = 'none'; console.log("Word not found"); } }) })
可选优化
如果不需要完全匹配,只要输入包含关键词就显示,可以把全等判断改成includes:
if (wordsHarmi[index].toLowerCase().includes(searchString))
内容的提问来源于stack exchange,提问作者Vanessa
相关产品推荐
相关产品推荐

