一、簡介
| 屬性 |
描述 |
| 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>