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







