js实现页面切换
使用 location.href 或 location.replace
通过修改 window.location 对象的属性实现页面跳转:
location.href = "新页面URL":跳转并保留历史记录,用户可通过浏览器后退按钮返回原页面。location.replace("新页面URL"):替换当前页面,不保留历史记录。
// 示例:跳转到新页面
document.getElementById("btn").addEventListener("click", () => {
window.location.href = "https://example.com";
});
使用 window.open
在新窗口或标签页中打开页面:

window.open("https://example.com", "_blank"); // "_blank" 表示新标签页
使用 history.pushState 或 replaceState(单页应用)
适用于单页应用(SPA),无刷新修改URL:

history.pushState(state, title, url):添加新历史记录。history.replaceState(state, title, url):替换当前历史记录。
// 示例:动态修改URL但不刷新页面
history.pushState({ page: 1 }, "Page 1", "/page1");
使用 <a> 标签模拟点击
通过JavaScript触发标签的点击事件:
const link = document.createElement("a");
link.href = "https://example.com";
link.target = "_blank"; // 可选:新标签页打开
link.click();
表单提交跳转
通过动态提交表单实现跳转:
const form = document.createElement("form");
form.method = "GET";
form.action = "https://example.com";
document.body.appendChild(form);
form.submit();
注意事项
- 安全性:避免使用
javascript:伪协议(如location.href = "javascript:alert(1)"),可能引发XSS漏洞。 - 单页应用:推荐结合框架(如React Router、Vue Router)管理路由。
- SEO:动态生成的跳转可能影响搜索引擎抓取,静态链接更友好。
根据需求选择合适方法,普通跳转推荐 location.href,单页应用推荐路由库。






