You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vanilla JS输入框自动提示值不匹配后提示仍显示问题

问题根因

你的代码存在两处逻辑缺失,导致无匹配结果时不会清空已渲染的提示列表:

  • outputHTML 函数仅在匹配结果数量大于0时才修改提示容器内容,当无匹配结果时不会主动清空之前渲染的旧提示
  • searchSpecies 函数仅在输入内容为空时做了清空操作,未覆盖「输入有内容但无匹配结果」的场景

修复方案

修改outputHTML函数,增加无匹配时的清空逻辑即可:

const specieInput = document.querySelector('#specie_input');
const suggestions = document.querySelector('.suggestions');

const searchSpecies = async searchText => {
    let my_data = networkJSON.full_data;
    
    let matches = my_data.filter(item => {
        const regex = new RegExp(`^${searchText}`, 'gi');
        return item.specie.match(regex);
    });

    if (searchText.length === 0){
        matches = [];
    }
    
    outputHTML(matches);
};

// 修复后的结果渲染函数
const outputHTML = matches => {
    if(matches.length > 0) {
        const html = matches.map(match => `
            <div class="card card-body">
                <h4>${match.specie} - ${match.rate}</h4>
            </div>
        `
        ).join('');
        suggestions.innerHTML = html;
    } else {
        // 无匹配结果时清空提示容器
        suggestions.innerHTML = '';
    }
}

specieInput.addEventListener('input', () => searchSpecies(specieInput.value));

修改后每次输入触发搜索时,无论是否有匹配结果都会更新提示容器内容,当输入内容无匹配项时,提示会自动关闭。


内容的提问来源于stack exchange,提问作者Raging Vids

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:06:03