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

JavaScript搜索无结果跳转功能实现求助

搜索功能无结果跳转的代码修改方案

用户需求

我正在尝试为现有的JavaScript搜索功能添加无结果跳转功能,但始终无法实现。希望能在我提供的现有代码基础上进行修改,而非替换全部代码,请告知修改内容及位置,感谢帮助。

现有代码

JavaScript代码

function openPage() {
        var x = document.getElementById("search").value;
             x = x.replace(/\b\w/g, (firstLetter) => firstLetter.toUpperCase());

//=======================================================================================

            if (x === "Aaron Carter") { 
                 window.open("files/aaroncarter.html");
            }

            if (x === "Albert Einstein") {
                window.open ("files/alberteinstein.html");
            }

            if (x === "Alex Higgins") {
                window.open ("files/alexhiggins.html");
            }
            }

HTML代码

<form action="" style="margin-bottom: 40px;">
                <div class="input-group">
                  <input type="search" id="search" autocomplete="off" onchange="openPage()"  class="form-control rounded-pill rounded-end-0 border-0 ps-4" placeholder="Search... e.g. Stan Laurel">
                  <button type="button" id="button" onclick="openPage()" value="Chercher" class="btn btn-primary rounded-pill rounded-start-0 shadow-none">
                    <i class="fa fa-search"></i>
                  </button>
                </div>
              </form>  

修改方案(仅修改JavaScript代码)

修改步骤:

  1. 在处理完搜索关键词x之后,新增布尔变量found用于标记是否匹配到结果
  2. 在每个匹配成功的if代码块内,将found设为true
  3. 在所有匹配判断的末尾,添加逻辑:如果found为false(无匹配结果),则跳转到预设的无结果页面

修改后的完整JavaScript代码

function openPage() {
        var x = document.getElementById("search").value;
             x = x.replace(/\b\w/g, (firstLetter) => firstLetter.toUpperCase());

// 新增:初始化结果匹配标志
            let found = false;

//=======================================================================================

            if (x === "Aaron Carter") { 
                 window.open("files/aaroncarter.html");
                 found = true; // 新增:标记已找到匹配结果
            }

            if (x === "Albert Einstein") {
                window.open ("files/alberteinstein.html");
                found = true; // 新增:标记已找到匹配结果
            }

            if (x === "Alex Higgins") {
                window.open ("files/alexhiggins.html");
                found = true; // 新增:标记已找到匹配结果
            }

// 新增:无结果时跳转,请替换成你的无结果页面路径
            if (!found) {
                window.open("files/no-result.html");
            }
            }

说明:

  • 将代码中的files/no-result.html替换为你实际的无结果页面路径即可
  • HTML代码无需修改,保持原样使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:40:18