js 实现跳转
使用 window.location.href 进行跳转
通过修改 window.location.href 可以直接跳转到指定 URL,这是最常用的跳转方法。
window.location.href = "https://example.com";
使用 window.location.replace 替换当前页面
replace 方法会替换当前页面,且不会在浏览历史中留下记录。
window.location.replace("https://example.com");
使用 window.open 在新窗口打开
window.open 可以指定 URL 在新窗口或标签页中打开,并可控制窗口属性。
window.open("https://example.com", "_blank");
使用 location.assign 进行导航
location.assign 会加载新页面并保留当前页面的历史记录。
window.location.assign("https://example.com");
使用 HTML 的 <a> 标签模拟跳转
通过 JavaScript 动态创建 <a> 标签并触发点击事件实现跳转。
const link = document.createElement("a");
link.href = "https://example.com";
link.click();
使用 meta 标签自动跳转
通过 JavaScript 动态插入 <meta> 标签实现自动跳转,适用于某些特殊场景(如 SEO 重定向)。
const meta = document.createElement("meta");
meta.httpEquiv = "refresh";
meta.content = "0;url=https://example.com";
document.head.appendChild(meta);
使用 history.pushState 或 history.replaceState 修改 URL
适用于单页应用(SPA),仅修改 URL 而不刷新页面。
// 添加新历史记录
history.pushState({}, "", "/new-page");
// 替换当前历史记录
history.replaceState({}, "", "/new-page");
使用 form.submit 提交表单跳转
适用于需要通过表单提交数据后跳转的情况。

const form = document.createElement("form");
form.method = "POST";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
注意事项
- 直接修改
window.location或使用assign会保留历史记录,replace则不会。 window.open可能被浏览器弹窗拦截器阻止,需确保在用户交互事件中触发。- SPA 跳转通常结合路由库(如 React Router、Vue Router)实现更复杂逻辑。






