window.location 是前端開發中最常用的對象之一,但它的各項屬性含義總是容易記混。本文做一個系統梳理,方便日後查閱。
以示例 URL 為例:https://b.a.com:88/index.php?name=kang&when=2011#first
window.location 和 document.location 互相等價,可以交換使用。
location 的 8 個屬性都是可讀寫的,但只有 href 與 hash 的寫操作有意義。改變 location.href 會重新定位到一個 URL;而修改 location.hash 會跳到當前頁面中對應 anchor(如 <a id="name"> 或 <div id="id">)的位置,且頁面不會被重新加載。
對於 URL:https://b.a.com:88/index.php?name=kang&how=#when=2011#first
此時 search 為 "?name=kang&how="(第一個問號之後),hash 為 "#when=2011#first"(第一個井號之後的內容)。
location.assign(url)
location.assign('https://www.baidu.com');
等同於 window.location = 'https://www.baidu.com'。這種方式會把新地址放入瀏覽器歷史棧,意味著轉到新頁面後「後退按鈕」仍可回到該頁面。
location.replace(url)
與 assign 類似,但會從歷史棧中刪除本頁面,也就是說跳轉後「後退按鈕」無法回到該頁面。目前 IE、Chrome 只是簡單跳轉,只有 Firefox 會真正刪除本頁面的歷史記錄。
location.reload(force)
重新載入當前頁面。force 為 true 時從服務器端重載,為 false 時從瀏覽器緩存重載,默認值為 false。