window.location 底下藏著一整組屬性,可以拆出協定、主機、連接埠、路徑、查詢字串與錨點。搞懂它們的分工,處理分頁、參數與路由時會輕鬆很多。
// 檔名或路徑
alert(window.location.pathname);
// 完整的 URL 字串
alert(window.location.href);
// 連接埠號
alert(window.location.port);
// 協定部分
alert(window.location.protocol);
// 井號 # 後面的錨點
alert(window.location.hash);
// hostname 與 port 的組合
alert(window.location.host);
// 問號後面的查詢字串
alert(window.location.search);
http:、https:,注意尾端含冒號。example.com:8080。<input type="button" value="重新整理" onclick="history.go(0)">
<input type="button" value="重新整理" onclick="location.reload()">
<input type="button" value="重新整理" onclick="location = location">
<input type="button" value="重新整理" onclick="location.assign(location)">
<input type="button" value="重新整理" onclick="document.execCommand('Refresh')">
<input type="button" value="重新整理" onclick="window.navigate(location)">
<input type="button" value="重新整理" onclick="location.replace(location)">
<input type="button" value="重新整理" onclick="document.URL = location.href">
這些寫法效果相近但語意有別:location.reload() 語意最明確;location.replace() 會用新頁面取代目前的歷史紀錄,重新整理後按上一頁不會回到原頁;而 document.execCommand 與 window.navigate 都屬於較早期的 API,新專案中建議以標準方法為主。