一、简介
属性 | 描述 |
hash |
从井号 (#) 开始的 URL(锚) |
host |
主机名和当前 URL 的端口号 |
hostname |
当前 URL 的主机名 |
href |
完整的 URL |
pathname |
当前 URL 的路径部分 |
port |
当前 URL 的端口号 |
protocol |
当前 URL 的协议 |
search |
从问号 (?) 开始的 URL(查询部分) |
assign |
加载新的文档 |
二、实例
1.hash
#百度统计
window. _hmt.push(['_trackPageview', "/" + window.location.hash])
2.host
#如果端口是 80,那么就没有端口
console.log(window.location.host)
3.hostname
#只有ip,没有端口
console.log(window.location.hostname)
4.href
document.getElementById("demo").innerHTML = "页面位置是 " + window.location.href;
5.pathname
#端口/之后的全路径,如/login?name=maple&pwd=123
document.getElementById("demo").innerHTML = "页面路径是 " + window.location.pathname;
6.port
document.getElementById("demo").innerHTML = "页面端口是 " + window.location.port;
7.protocol
#一般都是http或者是https
document.getElementById("demo").innerHTML = "页面协议是 " + window.location.protocol;
8.search
#将url中?中的参数遍历出来,location.search.substring(1)的值就是 "name=maple&pwd=123"
function getQueryByKey(key) {
let query = window.location.search.substring(1);
let vars = query.split("&");
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split("=");
if (pair[0] === key) {
return pair[1];
}
}
return (false);
}
9.assign
<html>
<head>
<script>
function newDoc() {
window.location.assign("https://www.baidu.com")
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>
</html>