js中实现页面跳转
使用 window.location.href
通过修改 window.location.href 属性实现跳转,这是最常见的方式。直接赋值为目标 URL 字符串即可跳转:
window.location.href = 'https://example.com';
使用 window.location.replace
与 href 类似,但会替换当前页面历史记录,用户无法通过浏览器后退按钮返回原页面:
window.location.replace('https://example.com');
使用 window.open
在新标签页或窗口中打开页面,可通过参数控制行为(如 _blank 表示新标签页):

window.open('https://example.com', '_blank');
使用 location.assign
与 href 效果相同,但显式调用方法更清晰:
window.location.assign('https://example.com');
使用 HTML 锚点(a 标签)
动态创建 <a> 标签并触发点击事件,适合需要模拟用户点击的场景:

const link = document.createElement('a');
link.href = 'https://example.com';
link.click();
使用 meta 标签刷新
通过动态插入 <meta> 标签实现自动跳转,常用于延迟跳转:
const meta = document.createElement('meta');
meta.httpEquiv = 'refresh';
meta.content = '3;url=https://example.com'; // 3秒后跳转
document.head.appendChild(meta);
使用 history.pushState/replaceState
适用于单页应用(SPA),仅更新 URL 而不刷新页面,需配合路由库使用:
history.pushState({}, '', '/new-path'); // 添加历史记录
history.replaceState({}, '', '/new-path'); // 替换当前记录
使用表单提交
通过动态表单提交实现跳转,适合需要传递数据的场景:
const form = document.createElement('form');
form.method = 'GET';
form.action = 'https://example.com';
document.body.appendChild(form);
form.submit();
注意事项
- 跳转前可监听事件或执行逻辑,但需避免阻塞跳转。
- 跨域限制可能影响部分跳转行为(如
window.open被浏览器拦截)。 - SPA 中推荐使用路由库(如 React Router、Vue Router)管理导航。






