在 JavaScript 中,Window.href 并不存在,你可能想说的是 Window.location.href(用于获取或设置当前页面的完整 URL)。以下是详细说明和常见用法:
1. window.location.href 的作用
- 获取当前页面的完整 URL
- 设置 URL 以实现页面跳转
示例代码
// 1. 获取当前页面的 URL
console.log(window.location.href);
// 输出示例: "https://www.example.com/path?query=123#section"
// 2. 跳转到新页面(修改 URL)
window.location.href = "https://www.google.com";
// 页面会立即跳转到 Google2. window.location 的其他常用属性
| 属性 / 方法 | 说明 | 示例 |
|---|---|---|
href | 完整 URL | "https://example.com/path?q=123" |
protocol | 协议(含 :) | "https:" |
host | 主机名 + 端口 | "www.example.com:8080" |
hostname | 主机名 | "www.example.com" |
port | 端口号 | "8080" |
pathname | 路径部分 | "/path/page.html" |
search | 查询参数(含 ?) | "?q=123" |
hash | 哈希值(含 #) | "#section" |
assign(url) | 跳转新页面(保留浏览历史) | window.location.assign("https://google.com") |
replace(url) | 跳转新页面(不保留历史) | window.location.replace("https://google.com") |
reload() | 重新加载当前页面 | window.location.reload() |
3. 常见用途
(1) 获取 URL 各部分
const url = window.location.href; // "https://example.com:8080/path?q=123#section"
console.log(window.location.protocol); // "https:"
console.log(window.location.host); // "example.com:8080"
console.log(window.location.pathname); // "/path"
console.log(window.location.search); // "?q=123"
console.log(window.location.hash); // "#section"(2) 页面跳转
// 方法1:直接赋值 href(推荐)
window.location.href = "https://google.com";
// 方法2:使用 assign()(效果相同,但可读性更好)
window.location.assign("https://google.com");
// 方法3:使用 replace()(不保留当前页在历史记录中)
window.location.replace("https://google.com");(3) 重新加载页面
// 强制从服务器重新加载(跳过缓存)
window.location.reload(true);
// 普通重新加载(可能使用缓存)
window.location.reload();4. 注意事项
window.locationvsdocument.location- 两者几乎等价,但
window.location是标准用法。 document.location是document的只读属性,返回window.location。
- 两者几乎等价,但
修改
href会触发页面跳转如果只是想解析 URL 而不跳转,可以用
new URL(url):const url = new URL("https://example.com/path?q=123"); console.log(url.pathname); // "/path"
单页应用(SPA)的路由
- 现代前端框架(如 React、Vue)通常使用
history.pushState()或 Hash 路由(#)来避免整页刷新。
- 现代前端框架(如 React、Vue)通常使用
5. 完整示例
<!DOCTYPE html>
<html>
<head>
<title>Location Demo</title>
</head>
<body>
<button onclick="navigateToGoogle()">跳转到 Google</button>
<button onclick="showUrlParts()">显示 URL 各部分</button>
<script>
function navigateToGoogle() {
window.location.href = "https://www.google.com";
}
function showUrlParts() {
alert(`
完整 URL: ${window.location.href}
协议: ${window.location.protocol}
主机: ${window.location.host}
路径: ${window.location.pathname}
查询参数: ${window.location.search}
哈希: ${window.location.hash}
`);
}
</script>
</body>
</html>总结
window.location.href是获取/设置当前 URL 的标准方式。- 修改它会触发页面跳转,而
assign()和replace()提供更可控的跳转方式。 - 使用
new URL()可以解析 URL 而不跳转。