Window Location 对象
JavaScript 中的 location 对象提供有关浏览器位置的信息,即 URL。它是 window 和 document 对象的内置属性。我们可以使用 window.location 或 document.location 访问它。
'location' 对象包含各种属性和方法,用于获取和操作浏览器位置 (URL) 的信息。
JavaScript Location 对象属性
我们可以使用 location 对象的属性来获取 URL 的信息:
- hash − 此属性用于设置或获取 URL 的锚点部分。
- host − 此属性用于设置或获取 URL 的主机名或端口号。
- hostname − 此属性用于设置主机名。
- href − 此属性用于设置或获取当前窗口的 URL。
- origin - 此属性返回 URL 的协议、域和端口。
- pathname - 此属性更新或获取路径名。
- port - 此属性更新或获取 URL 的端口。
- protocol - 此属性更新或获取协议。
- search − 此属性用于设置或获取 URL 的查询字符串。
语法
按照下面的语法访问 location 对象的属性和方法 -
window.location.property;
或
location.property;
你可以使用 'window' 对象来访问 'location' 对象。
在这里,我们通过示例演示了 location 对象的一些属性的使用。
示例:访问位置主机属性
location.host 属性从当前 URL 返回主机。但是,您也可以使用它来更改主机。
在下面的代码中,我们从 URL 中提取主机。你可以看到它返回 'www.qikepu.com'。
<html>
<body>
<div id="output"></div>
<script>
const host = location.host;
document.getElementById("output").innerHTML =
"The host of the current location is: " + host;
</script>
</body>
</html>
输出
示例:访问位置协议属性
location.protocol 属性用于在当前 URL 中使用。您还可以使用它来更新协议。
请尝试以下示例以使用 location.protocol 属性 -
<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The protocol of the current location is: " + location.protocol;
</script>
</body>
</html>
输出
示例:访问位置主机名属性
location.hostname 属性返回当前 URL 的主机名。您也可以将其用于主机名。
尝试以下示例使用 location.hostname 属性 –
<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The host name of the current location is: " + location.hostname;
</script>
</body>
</html>
输出
示例:访问 location pathname 属性
location.pathname 属性返回当前位置的路径名。您可以使用它设置路径名。
<html>
<body>
<div id = "output"> </div>
<script>
document.getElementById("output").innerHTML =
"The protocol of the current location is: " + location.pathname;
</script>
</body>
</html>
输出
JavaScript Location 对象方法
我们还可以使用 location 对象的方法导航到新的 URL -
- assign(url) − 此方法在指定的 URL 处加载新文档。
- replace(url) − 此方法将当前文档替换为指定 URL 处的新文档。
- reload() − 此方法重新加载当前文档。
JavaScript location assign() 方法
location.assign() 方法获取 URL 并更改当前窗口中的 URL。简而言之,它会打开一个新的网页。
语法
按照下面的语法在 JavaScript 中使用 location.assign() 方法 -
location.assign();
例
在下面的代码中,当您单击“转到主页”按钮时,它会将您重定向到 tutorialpoint 网站的主页。
<html>
<body>
<div id="output"></div>
<button onclick="changePage()">Go to Home Page</button>
<script>
let output = document.getElementById("output");
function changePage() {
window.location.assign("https://www.qikepu.com/");
}
</script>
</body>
</html>
位置对象属性列表
在这里,我们列出了 Location 对象的所有属性。
属性 | 描述 |
---|---|
hash | 设置或获取 URL 的锚点部分。 |
host | 设置或获取 URL 的主机名或端口号。 |
hostname | 设置主机名。 |
href | 设置或获取当前窗口的 URL。 |
origin | 返回 URL 的协议、域和端口。 |
pathname | 更新或获取路径名。 |
port | 更新或获取 URL 的端口。 |
protocol | 更新或获取协议。 |
search | 设置或获取 URL 的查询字符串。 |
Location 对象方法列表
在这里,我们列出了 Location 对象的所有方法。
方法 | 描述 |
---|---|
assign() | 在特定 URL 处加载资源。 |
reload() | 重新加载网页。 |
replace() | 将当前网页的资源替换为其他网页的资源。 |
toString() | 返回字符串格式的 URL。 |