1. 程式人生 > 其它 >JS Window Location

JS Window Location

宣告

該文部分程式碼和內容節選自菜鳥教程,僅用作個人學習,特此宣告

連結https://www.runoob.com/

JS Window Location

window.location 物件用於獲得當前頁面的地址 (URL),並把瀏覽器重定向到新的頁面

1、Window Location

window.location 物件在編寫時可不使用 window 這個字首

Window.Location的一些屬性:

  • location.hostname 返回 web 主機的域名
  • location.pathname 返回當前頁面的路徑和檔名
  • location.port 返回 web 主機的埠 (80 或 443)
  • location.protocol 返回所使用的 web 協議(http: 或 https:)

2、Location Href

location.href 屬性返回當前頁面的整個 URL。

document.write(location.href);//https://www.runoob.com/js/js-window-location.html

3、Location Pathname

location.pathname 屬性返回 URL 的路徑名

document.write(location.pathname);///js/js-window-location.html

4、Assign 和 Replace

  • location.assign() 方法載入新的文件

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>location.assign()</title>
    <script>
    function newDoc(){
        window.location.assign("http://www.hao123.com")
    }
    </script>
    </head>
    <body>
    <input type="button" value="載入新文件" onclick="newDoc()">
    </body>
    </html>
    
  • location.replace() 方法將當前文件替換為新的文件

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>location.replace()</title>
    <script>
    function newDoc(){
        window.location.replace("http://www.hao123.com")
    }
    </script>
    </head>
    <body>
    <input type="button" value="載入新文件" onclick="newDoc()">
    </body>
    </html>
    
  • 二者的區別

    • replace() 從文件歷史記錄中刪除當前 URL。
    • 使用 replace() 時,無法使用 “後退” 導航回原始文件。