JS Location
创建于 2024-12-03 /
32
字体:
[默认]
[大]
[更大]
window.location
对象可用于获取当前页面地址(URL)并把浏览器重定向到新页面。
Window Location
window.location
对象可不带 window 前缀书写。
一些例子:
window.location.href
返回当前页面的 href (URL)window.location.hostname
返回 web 主机的域名window.location.pathname
返回当前页面的路径或文件名window.location.protocol
返回使用的 web 协议(http: 或 https:)window.location.assign()
加载新文档
Window Location Href
window.location.href 属性返回当前页面的 URL。
实例
显示当前页面的 href (URL):
document.getElementById("demo").innerHTML ="Page location is " + window.location.href;
结果是:
亲自试一试 »
Window Location 主机名
window.location.hostname 属性返回(当前页面的)因特网主机的名称。
实例
显示主机的名称:
document.getElementById("demo").innerHTML ="Page hostname is " + window.location.hostname;
结果是:
亲自试一试 »
Window Location 路径名
window.location.pathname 属性返回当前页面的路径名。
实例
显示当前 URL 的路径名:
document.getElementById("demo").innerHTML ="Page path is " + window.location.pathname;
结果是:
亲自试一试 »
Window Location 协议
window.location.protocol 属性返回页面的 web 协议。
实例
显示 web 协议:
document.getElementById("demo").innerHTML ="Page protocol is " + window.location.protocol;
结果是:
亲自试一试 »
Window Location 端口
window.location.port 属性返回(当前页面的)互联网主机端口的编号。
实例
显示主机的端口号:
document.getElementById("demo").innerHTML ="Port number is " + window.location.port;
结果是:
亲自试一试 »
大多数浏览器不会显示默认端口号(http 为 80,https 为 443)。
Window Location Assign
window.location.assign() 方法加载新文档。
实例
加载新文档:
<html><head>
<script>
function newDoc() {
window.location.assign("https://www.w3ccoo.com")
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>
</html> 亲自试一试 »
0 人点赞过