JavaScript页面跳转最直接可靠的方式是操作window.location对象:location.href赋值触发新记录跳转,location.replace()替换当前历史项,location.assign()为冗余方法;需校验URL合法性并编码参数,且跳转后代码仍可能执行。
JavaScript 中实现页面跳转,最直接可靠的方式就是操作 window.location 对象。它不是“可选方案”,而是浏览器原生支持、语义明确、兼容性极佳的核心机制。
直接给 location.href 赋一个新 URL 字符串,浏览器会立即导航过去,行为等同于用户点击链接。
"./about.html")、绝对路径(如 "/admin/list")、完整 URL(如 "https://example.com")window.location.href()(带括号是调用函数,会报 TypeError: location.href is not a function)location.href = "./dashboard.html"; // 或 window.location.href = "https://github.com";
当你要跳转但不想在历史栈中留下当前页(比如登录成功后跳首页、表单提交后跳结果页),用 replace() 更合适。
href 赋值完全一致,只是语义和历史行为不同location.replace("/order/confirmed");
// 等价于
window.location.replace("https://shop.example/order/confirmed");
) 和 href 赋值几乎没区别,但极少用assign() 是 href 赋值的函数式等价写法,行为完全一致:新增历史记录、可后退、触发完整加载。
location.assign("..."),因为 location.href = "..." 更简洁直观常见错误是把用户输入或接口数据直接拼进 URL,导致跳转失败或 XSS 漏洞。
location.href = "/user?id=" + userId —— 若 userId 是 "1';alert(1)//",就危险了encodeURIComponent() 编码:"/user?id=" + encodeURIComponent(userId)
URL 构造函数校验和拼接:const url = new URL("/search", window.location.origin);
url.searchParams.set("q", userInput);
location.href = url.toString();if (url.protocol === "http:" || url.protocol === "https:") { location.href = url; },避免 javascript: 或 data: 伪协议执行真正容易被忽略的是:location 操作是同步触发但异步生效的。你在 location.href = ... 后面写的代码(比如 log、状态清理)大概率仍会执行,除非你主动用 return 或 throw 阻断。别假设跳转后 JS 就立刻停了。