用js实现页面跳转
使用 window.location.href 进行跳转
通过修改 window.location.href 属性实现页面跳转,这是最常用的方法。
window.location.href = "https://example.com";
使用 window.location.replace 替换当前页面
replace 方法会替换当前页面,不会在浏览历史中留下记录。
window.location.replace("https://example.com");
使用 window.open 在新窗口打开
window.open 可以在新标签页或窗口中打开页面,并可控制窗口属性。
window.open("https://example.com", "_blank");
使用 location.assign 加载新页面
assign 方法会加载新页面,并在浏览历史中保留原页面记录。
window.location.assign("https://example.com");
使用 meta 标签自动跳转
在 HTML 的 <head> 中添加 <meta> 标签,设置自动跳转。
<meta http-equiv="refresh" content="5;url=https://example.com">
使用表单提交跳转
通过动态创建表单并提交实现跳转。
const form = document.createElement("form");
form.method = "GET";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
使用 history.pushState 或 replaceState(单页应用)
适用于单页应用(SPA),仅更新 URL 而不刷新页面。
history.pushState({}, "", "/new-page");
// 或
history.replaceState({}, "", "/new-page");
使用 a 标签模拟点击
动态创建 <a> 标签并触发点击事件实现跳转。
const link = document.createElement("a");
link.href = "https://example.com";
link.click();
注意事项
replace和assign的区别在于是否保留历史记录。window.open可能被浏览器弹窗拦截器阻止。- 单页应用跳转需配合前端路由库(如 React Router、Vue Router)。







