js实现跳转
使用 window.location 跳转
通过修改 window.location.href 或直接使用 window.location 实现页面跳转,适用于普通跳转或带参数的 URL。
// 方法1:直接赋值
window.location.href = 'https://example.com';
// 方法2:简写形式
window.location = 'https://example.com';
// 带参数的跳转
window.location.href = 'https://example.com?param=value';
使用 location.assign()
location.assign() 方法会加载新文档并保留浏览器历史记录,允许用户通过后退按钮返回原页面。
location.assign('https://example.com');
使用 location.replace()
location.replace() 直接替换当前页面,不保留历史记录,用户无法通过后退按钮返回。
location.replace('https://example.com');
使用 window.open()
在新标签页或窗口中打开链接,可通过参数控制打开方式。
// 新标签页打开(默认)
window.open('https://example.com');
// 新窗口打开
window.open('https://example.com', '_blank');
// 当前窗口打开(等效于 location.href)
window.open('https://example.com', '_self');
使用 meta 标签跳转
通过动态插入 <meta> 标签实现延迟跳转,常用于页面自动跳转场景。
// 3秒后跳转
const meta = document.createElement('meta');
meta.httpEquiv = 'refresh';
meta.content = '3;url=https://example.com';
document.head.appendChild(meta);
使用表单提交跳转
通过动态创建表单并提交实现 POST 跳转,适用于需要传递表单数据的场景。
const form = document.createElement('form');
form.method = 'POST';
form.action = 'https://example.com';
const input = document.createElement('input');
input.type = 'hidden';
input.name = 'data';
input.value = 'example';
form.appendChild(input);
document.body.appendChild(form);
form.submit();
使用 History API
通过 history.pushState() 或 history.replaceState() 修改浏览器地址栏而不刷新页面,适用于单页应用(SPA)。
// 添加历史记录并跳转
history.pushState({}, '', '/new-path');
// 替换当前历史记录
history.replaceState({}, '', '/new-path');
注意事项
- 使用
window.open()可能被浏览器拦截,需确保由用户触发(如点击事件)。 location.replace()不保留历史记录,适合登录后跳转等场景。- History API 需配合前端路由框架使用,单独调用可能需手动处理页面内容更新。






