好的!下面是关于 window.location.href 的详细介绍及常见用法示例。


window.location.href 详解及使用


1. 什么是 window.location.href

  • window.location 是浏览器中表示当前页面URL的对象。
  • window.location.href 是该对象的一个属性,表示当前页面的完整URL字符串。
  • 你可以通过读取它获取当前页面地址,也可以通过赋值给它实现页面跳转。

2. 主要功能

用法说明
读取 window.location.href获取当前页面的URL字符串
设置 window.location.href跳转到指定URL,相当于改变浏览器地址栏并加载新页面

3. 使用示例

3.1 获取当前页面URL

console.log(window.location.href);
// 例如输出: "https://www.example.com/path/page.html?query=123#section"

3.2 页面跳转到新地址

window.location.href = "https://www.google.com";

浏览器会跳转到谷歌首页。

3.3 相当于点击链接跳转

给按钮绑定点击事件跳转:

<button onclick="window.location.href='https://www.baidu.com'">跳转百度</button>

4. 与其他 location 属性对比

属性作用页面跳转是否可回退
window.location.href获取或设置完整URL是,浏览器历史可回退
window.location.assign(url)功能等同于设置href
window.location.replace(url)替换当前页面,不保留历史否,不能回退
window.location.reload()刷新当前页面

5. 注意事项

  • 使用 window.location.href = ... 会新增浏览记录,用户可以点击“后退”返回原页面。
  • 若不希望用户回退到原页面,可使用 window.location.replace(url)
  • 修改 href 会触发页面跳转,期间JS执行会暂停。

6. 结合查询参数跳转示例

// 动态添加查询参数跳转
const userId = 123;
window.location.href = `https://example.com/profile?user=${userId}`;

如果你需要,我可以帮你写更详细的页面跳转控制示例,或者单页应用中路由跳转的区别说明,告诉我!

明白!下面是关于 window.location.href 的各种常见代码示例,帮你直观理解它的读取和跳转用法。


window.location.href 代码示例


1. 获取当前页面URL

// 输出当前页面完整URL
console.log("当前页面地址是:" + window.location.href);

2. 页面跳转到指定网址

// 立即跳转到百度首页
window.location.href = "https://www.baidu.com";

3. 点击按钮跳转

<button onclick="window.location.href='https://www.google.com'">
  跳转到Google
</button>

4. 通过JS函数动态跳转

function goToPage(page) {
  window.location.href = page;
}

// 调用函数跳转
goToPage("https://www.example.com/about");

5. 跳转并带参数

const userId = 42;
window.location.href = `https://www.example.com/user?id=${userId}`;

6. 监听当前URL变化(用window.location.href读取)

setInterval(() => {
  console.log("当前URL是:" + window.location.href);
}, 5000);  // 每5秒输出一次当前URL

7. 使用 window.location.replace() 替代 href,不保留历史

// 跳转到新页面,无法通过后退返回
window.location.replace("https://www.nosite.com");

8. 判断当前页面是否是首页

if (window.location.href === "https://www.example.com/") {
  console.log("当前页面是首页");
} else {
  console.log("当前不是首页");
}