DIV CSS 佈局教程網

JavaScript 取得當前頁面網址的各種屬性
編輯:JavaScript綜合知識     

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);

各屬性的定位

  • href:完整網址,讀寫皆可,賦值等同於跳轉。
  • protocol:如 http:、https:,注意尾端含冒號。
  • host:主機名稱加連接埠,例如 example.com:8080。
  • hostname:只有主機名稱,不含連接埠。
  • port:連接埠;使用預設埠時通常回傳空字串。
  • pathname:路徑部分,不含網域與參數。
  • search:查詢字串,含最前面的問號。
  • hash:錨點,含最前面的井號,單頁應用中常用來做路由。

附帶:重新整理頁面的幾種寫法

<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,新專案中建議以標準方法為主。

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