在開發中,我們常需要取得當前頁面的網域名稱、完整網址等資訊,例如用於分享、統計或動態生成連結。JavaScript 透過 location 物件就能輕鬆取得這些資料。
代碼如下:
<script> //獲取域名 var k_host = window.location.host; var k_host2 = document.domain; //獲取頁面完整地址 var k_url = window.location.href; </script>
其中 window.location.host 與 document.domain 都能取得網域名稱,而 window.location.href 則返回頁面的完整網址。
此外,location 物件還提供了其他實用的屬性:
掌握這些屬性,就能靈活解析與操作當前頁面的網址資訊。