搜索栏Javascript _self标签失效,如何实现页面在当前窗口打开?
解决搜索栏在当前窗口打开页面的问题
你的问题出在两个核心点:
- 前两个
window.open调用未指定_self目标参数,浏览器默认会打开新窗口 - 第二个判断用独立
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
相关产品推荐
相关产品推荐

