DIV CSS 佈局教程網

JS 取得當前頁面路徑:location 各屬性用途與頁面重新整理寫法
編輯:關於JavaScript     

window.location 提供了一組屬性,可以取得或設定目前網址的各個組成部分。

常用屬性

// 取得路徑與檔名
<script>alert(window.location.pathname)</script>

// 取得完整的 URL 字串
<script>alert(window.location.href);</script>

// 取得與 URL 關聯的埠號
<script>alert(window.location.port)</script>

// 取得 URL 的協定部分(http: / https: / file:)
<script>alert(window.location.protocol)</script>

// 取得 href 中井號「#」後面的片段
<script>alert(window.location.hash)</script>

// 取得 hostname 與 port 的組合
<script>alert(window.location.host)</script>

// 取得 href 中問號後面的查詢字串
<script>alert(window.location.search)</script>

以一個網址為例

對 https://example.com:8080/app/page.html?id=1#top 而言:

protocolhttp:
hostexample.com:8080
hostnameexample.com
port8080
pathname/app/page.html
search?id=1
hash#top
href完整網址

頁面重新整理的幾種寫法

<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.reload(true)(此參數在現代瀏覽器已無效果,需改用後端 no-cache header 或附加時間戳)。

history.go(0) 效果等同重新整理,但語意是「回到目前歷史紀錄」,較不直觀。location = location 與 location.assign(location) 是重新導向到同一個網址,副作用是會在瀏覽器歷史中留下紀錄,按上一頁可能不會離開。location.replace(location) 則會取代目前的歷史紀錄,不留痕跡。

document.execCommand('Refresh') 與 window.navigate() 都是舊 IE 專屬且已廢棄,不建議使用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved