JavaScript
/ Location
Location
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 = "页面位置是 " + window.location.href;
结果是:
页面位置是 http://www.php.cn/js/js_window_location.asp运行实例 »
点击 "运行实例" 按钮查看在线实例
Window Location 主机名
window.location.hostname 属性返回(当前页面的)因特网主机的名称。
实例
显示主机的名称:
document.getElementById("demo").innerHTML = "页面主机名是 " + window.location.hostname;
结果是:
页面主机名是 www.php.cn运行实例 »
点击 "运行实例" 按钮查看在线实例
Window Location 路径名
window.location.pathname 属性返回当前页面的路径名。
实例
显示当前 URL 的路径名:
document.getElementById("demo").innerHTML = "页面路径是 " + window.location.pathname;
结果是:
页面路径是 /js/js_window_location.asp运行实例 »
点击 "运行实例" 按钮查看在线实例
Window Location 协议
window.location.protocol 属性返回页面的 web 协议。
实例
显示 web 协议:
document.getElementById("demo").innerHTML = "页面协议是 " + window.location.protocol;
结果是:
页面协议是 http:运行实例 »
点击 "运行实例" 按钮查看在线实例
Window Location 端口
window.location.port 属性返回(当前页面的)互联网主机端口的编号。
实例
显示主机的端口号:
document.getElementById("demo").innerHTML = "端口号是: " + window.location.port;
运行实例 »点击 "运行实例" 按钮查看在线实例
大多数浏览器不会显示默认端口号(http 为 80,https 为 443)。
Window Location Assign
window.location.assign() 方法加载新文档。
实例
加载新文档:
<html>
<head>
<script>
function newDoc() {
window.location.assign("https://www.php.cn")
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>
</html>
运行实例 »点击 "运行实例" 按钮查看在线实例