📌  相关文章
📜  JavaScript | window.location 和 document.location 对象(1)

📅  最后修改于: 2023-12-03 15:31:39.414000             🧑  作者: Mango

JavaScript | window.location 和 document.location 对象

在 JavaScript 中,window.locationdocument.location 都是用于获取当前网页 URL 相关信息的对象。

window.location

window.location 是一个代表当前窗口中显示文档的 Location 对象。

通过 window.location,可以获取当前网页的 URL、协议、主机、端口、路径以及查询参数等相关信息。例如:

console.log(window.location.href);       // 当前网页完整 URL
console.log(window.location.protocol);   // 协议(http 或 https)
console.log(window.location.host);       // 主机(例如 www.example.com)
console.log(window.location.port);       // 端口(例如 80 或 443)
console.log(window.location.pathname);   // 路径(例如 /index.html)
console.log(window.location.search);     // 查询参数(例如 ?id=123)
console.log(window.location.hash);       // 锚点(例如 #section1)

通过 window.location,还可以修改当前网页的 URL,从而实现页面跳转或刷新等功能。例如:

window.location.href = 'http://www.example.com';   // 重定向到一个新网页
window.location.reload();                         // 刷新当前网页
document.location

document.location 也是一个代表当前窗口中显示文档的 Location 对象。

window.location 不同的是,document.location 的作用是用于获取当前网页的 URL 并对其进行修改,从而实现页面跳转或刷新等功能。例如:

document.location.href = 'http://www.example.com';   // 重定向到一个新网页
document.location.reload();                         // 刷新当前网页

window.location 类似,document.location 可以获取当前网页的 URL 相关信息。例如:

console.log(document.location.href);       // 当前网页完整 URL
console.log(document.location.protocol);   // 协议(http 或 https)
console.log(document.location.host);       // 主机(例如 www.example.com)
console.log(document.location.port);       // 端口(例如 80 或 443)
console.log(document.location.pathname);   // 路径(例如 /index.html)
console.log(document.location.search);     // 查询参数(例如 ?id=123)
console.log(document.location.hash);       // 锚点(例如 #section1)

需要注意的是,虽然 document.location 也可以用于修改当前网页的 URL,但是它在一些老版本的浏览器中可能会出现不兼容的问题。因此,建议优先使用 window.location 实现页面跳转或刷新等功能。