js实现url跳转
使用 window.location.href 进行跳转
通过修改 window.location.href 属性,可以直接跳转到指定的 URL。这是最常用的方法之一:
window.location.href = "https://example.com";
使用 window.location.replace 替换当前页面
replace 方法会替换当前页面,不会在浏览历史中留下记录:
window.location.replace("https://example.com");
使用 window.location.assign 跳转
assign 方法与 href 类似,但更显式地表示跳转行为:
window.location.assign("https://example.com");
使用 window.open 在新窗口打开
window.open 可以在新窗口或标签页中打开 URL,并可控制窗口属性:
window.open("https://example.com", "_blank");
使用 <a> 标签模拟点击
动态创建 <a> 标签并触发点击事件,适用于需要模拟用户交互的场景:
const link = document.createElement("a");
link.href = "https://example.com";
link.target = "_blank";
link.click();
使用 history.pushState 修改 URL 但不跳转
适用于单页应用(SPA),仅修改 URL 而不刷新页面:
history.pushState({}, "", "https://example.com/new-path");
使用 meta 标签自动跳转
通过 HTML <meta> 标签实现自动跳转,适用于纯 HTML 场景:
<meta http-equiv="refresh" content="0; url=https://example.com">
注意事项
- 使用
replace会跳过历史记录,适合不希望用户返回的场景。 window.open可能被浏览器拦截,需确保由用户交互触发。- 单页应用推荐使用
pushState或框架自带的路由方法(如 React Router、Vue Router)。







