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

搜索栏Javascript _self标签失效,如何实现页面在当前窗口打开?

解决搜索栏在当前窗口打开页面的问题

你的问题出在两个核心点:

  1. 前两个window.open调用未指定_self目标参数,浏览器默认会打开新窗口
  2. 第二个判断用独立if而非else if,会导致逻辑错误——比如输入"Aaron Carter"时,第一个条件执行后仍会走到else分支打开错误页面

最小修改方案(保留window.open写法)

只需要给前两个window.open加上_self参数,同时把第二个if改成else if:

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", "_self");
    } else if (x === "Albert Einstein") {
        window.open("files/alberteinstein.html", "_self");
    } else {
        window.open("files/error.html", "_self");
    }
}

更直观的替代方案(用location.href跳转)

如果只是要在当前窗口跳转,window.location.href比window.open更贴合需求,不需要额外指定目标参数,代码也更简洁:

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

    if (x === "Aaron Carter") { 
        window.location.href = "files/aaroncarter.html";
    } else if (x === "Albert Einstein") {
        window.location.href = "files/alberteinstein.html";
    } else {
        window.location.href = "files/error.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.27 14:45:17