window.location 和 document.location 有什麼區別?
window.location 屬性
視窗的 location 屬性(即 window.location)是對 Location 物件的引用;它表示在該視窗中顯示的文件的當前 URL。
由於 window 物件位於作用域鏈的頂部,因此無需 window 字首即可訪問 window.location 物件的屬性。例如,window.location.href 可以寫成 location.href。下一節將向您展示如何使用 window 物件的 location 物件屬性來獲取頁面的 URL 以及主機名、協議等。
您可以使用 window.location.href 屬性獲取當前頁面的完整 URL。
示例
以下示例演示瞭如何使用 window.location.href 獲取頁面 URL:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JavaScript Get Current URL</title> </head> <body> <script> function getURL() { alert("The URL of this page is: " + window.location.href); } </script> <button type="button" onclick="getURL();">Get Page URL</button> </body> </html>
執行上述程式後,將顯示一個按鈕,上面寫著“獲取頁面 URL”。單擊此按鈕,將顯示當前頁面的 URL。如果我們單擊名為“獲取頁面 URL”的按鈕,我們將得到當前 URL 作為輸出。
document.location 屬性
這是一個只讀屬性,它返回當前文件的 URL。以下是 JavaScript 中 document.location 屬性的示例:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document.location Properties</title> </head> <body> <script> document.write("The pathname of this file is:"+ document.location.pathname + "<br>"); document.write("The Protocol used is:"+ document.location.protocol + "<br>"); </script> </body> </html>
使用 document.location 載入 URL
要使 document.location 載入 URL,應將其賦值給一個字串,然後載入字串中的 URL。要使用新文件進行賦值或載入,可以使用以下示例。
示例
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document.location </title> </head> <body> <h2>Document.location</h2> <p>To load a new page</p> <script> function newPage() { document.location.assign("https://tutorialspoint.tw/"); } </script> <button type="button" onclick="newPage() ;"> Click </button> </body> </html>
window.location 和 document.location 的區別
window.location 和 document.location 物件都用於獲取 URL,但區別在於:
- window.location 在所有瀏覽器中都是可讀寫的。
- 而 document.location 在 Internet Explorer 中是隻讀的,在基於 Gecko 的瀏覽器中是可讀寫的。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP