js实现换页
使用 window.location 实现页面跳转
通过修改 window.location.href 可以直接跳转到新页面:
window.location.href = "https://example.com/newpage.html";
如果需要强制刷新当前页面:
window.location.reload(true);
使用 history.pushState 实现无刷新换页
适用于单页应用(SPA),通过修改浏览器历史记录实现无刷新跳转:
history.pushState({}, "", "/newpage");
监听路由变化需配合 popstate 事件:
window.addEventListener("popstate", () => {
console.log("URL changed:", window.location.pathname);
});
表单提交跳转
通过动态创建表单并提交实现页面跳转:
const form = document.createElement("form");
form.method = "POST";
form.action = "/submit";
document.body.appendChild(form);
form.submit();
使用 window.open 打开新窗口
在新标签页或窗口中打开页面:
window.open("https://example.com", "_blank");
可通过参数控制窗口属性:
window.open("/page", "_blank", "width=600,height=400");
使用 meta 标签自动跳转
在 HTML 中通过 <meta> 实现定时跳转:
<meta http-equiv="refresh" content="5;url=https://example.com">
JavaScript 动态设置:
document.head.innerHTML += '<meta http-equiv="refresh" content="2;url=/target">';
注意事项
- 使用
window.location会触发页面卸载,可能丢失未保存的数据。 history.pushState需确保后端路由配置支持,避免直接访问子路由时返回 404。- 跨域限制下
window.open可能被浏览器拦截,需用户主动触发(如点击事件)。







