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

如何实现搜索栏无匹配结果时显示‘Sem resultado’(HTML-CSS-JS)

实现搜索无结果时显示葡萄牙语提示

我已经完成了搜索栏的过滤功能,现在需要添加逻辑:当输入内容未匹配到任何条目时,显示葡萄牙语提示文本Sem resultado(意为“无结果”)。HTML中已创建对应的提示元素,以下是修改方案:

修改后的JavaScript代码

function search(){
    var input, filter, dropdown, li, a, i, textvalue;
    input = document.getElementById('searchbarinput');
    filter = input.value.toUpperCase();
    dropdown = document.getElementById("searchbardropdown");
    li = dropdown.getElementsByTagName('li');
    noresult = document.getElementById("searchbarnoresult").parentNode; // 获取提示元素所在的li
    let matchCount = 0; // 统计匹配的条目数

    for(i=0; i < li.length; i++){
        a = li[i].getElementsByTagName("a")[0];
        // 跳过提示元素的li,不参与过滤
        if(a.id === "searchbarnoresult") continue;
        
        textvalue = a.textContent || a.innerText;
        if(textvalue.toUpperCase().indexOf(filter)>-1){
            li[i].style.display = "";
            matchCount++; // 匹配成功,计数器加1
        }
        else{
            li[i].style.display = "none";
        }
    }

    // 根据匹配数量控制提示的显示/隐藏
    if(matchCount === 0){
        noresult.style.display = "";
    } else {
        noresult.style.display = "none";
    }
}

逻辑说明

  1. 添加匹配计数器:用matchCount统计过滤后显示的正常条目数量;
  2. 跳过提示元素:在循环中判断当前条目是否是提示元素,若是则跳过,避免被过滤逻辑影响;
  3. 控制提示显示:循环结束后,若matchCount为0,说明没有匹配条目,显示提示;否则隐藏提示。

其他说明

原HTML和CSS无需修改,仅需更新上述JavaScript代码即可实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:20:42