天天看點

window.location 對象中各種方法的用途

一、簡介

屬性 描述
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>