在js中实现页面跳转
使用 window.location.href
通过修改 window.location.href 属性实现跳转:
window.location.href = "https://example.com";
这种方式会保留浏览历史,用户可通过后退按钮返回上一页。
使用 window.location.replace
通过 window.location.replace 实现跳转且不保留历史记录:
window.location.replace("https://example.com");
适用于不需要用户返回的场景,如登录后跳转。
使用 window.open
在新窗口或标签页中打开页面:
window.open("https://example.com", "_blank");
第二个参数可指定打开方式(如 _self 在当前窗口打开)。

使用 HTML 锚点
通过动态创建 <a> 标签实现跳转:
const link = document.createElement("a");
link.href = "https://example.com";
link.target = "_blank"; // 可选
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
使用 meta 标签刷新
通过插入 <meta> 标签实现自动跳转:
const meta = document.createElement("meta");
meta.httpEquiv = "refresh";
meta.content = "0;url=https://example.com";
document.head.appendChild(meta);
content 中的 0 表示延迟时间(秒)。

使用 history.pushState
通过 History API 修改 URL 而不刷新页面:
history.pushState({}, "", "/new-page");
适用于单页应用(SPA),需配合路由库使用。
使用表单提交
通过动态创建表单实现跳转:
const form = document.createElement("form");
form.method = "GET";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
适用于需要传递参数的场景。
注意事项
- 跨域限制:某些方法受同源策略限制。
- 用户体验:避免频繁自动跳转。
- SEO 影响:部分方法可能不利于搜索引擎抓取。
- 现代框架:推荐使用 React Router、Vue Router 等专用路由库。






