Location對象
Location 對象包含有關當前 URL 的信息。
Location 對象是 window 對象的一部分,可通過 window.Location
屬性對其進行訪問。
Note
CONTENT
Location 對象屬性
屬性 | 描述 |
---|---|
hash | 返回一個URL的錨部分 |
host | 返回一個URL的主機名和端口 |
hostname | 返回URL的主機名 |
href | 返回完整的URL |
pathname | 返回的URL路徑名。 |
port | 返回一個URL服務器使用的端口號 |
protocol | 返回一個URL協議 |
search | 返回一個URL的查詢部分 |
Location 對象方法
方法 | 說明 |
---|---|
assign() | 載入一個新的文檔 |
reload() | 重新載入當前文檔 |
replace() | 用新的文檔替換當前文檔 |
Location對象屬性
console.log(location.hash);
// #part2
console.log(location.host);
// www.runoob.com
console.log(location.hostname);
// www.runoob.com
console.log(location.href);
// https://www.runoob.com/jsref/prop-loc-href.html
console.log(location.pathname);
// /jsref/prop-loc-pathname.html
console.log(location.port);
//
console.log(location.protocol);
// https:
// 假設當前的URL就是http://www.runoob.com/submit.htm?email=someone@ example.com:
console.log(location.search);
// ?email=someone@example.com
定義和用法
hash
屬性是一個可讀可寫的字符串,該字符串是 URL 的錨部分(從 # 號開始的部分)。
host
屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的主機名稱和端口號。
hostname
屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的主機名。
href
屬性是一個可讀可寫的字符串,可設置或返回當前顯示的文檔的完整 URL。
pathname
屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的路徑部分。
port
屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的端口部分。
? 注意:如果端口號就是80(這是默認的端口號),無需指定。
protocol
屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的協議。
search
屬性是一個可讀可寫的字符串,可設置或返回當前 URL 的查詢部分(問號 ? 之后的部分)。
語法
location.hash
location.host
location.hostname
location.href
location.pathname
location.port
location.protocol
location.search
Location對象方法
<input type="button" value="載入新文檔" onclick="window.location.assign('http://www.runoob.com')">
<input type="button" value="重新加載頁面" onclick="location.reload()">
<input type="button" value="載入新文檔替換當前頁面" onclick="window.location.replace('http://www.runoob.com')">
定義和用法
assign()
方法加載一個新的文檔。
reload()
方法用于刷新當前文檔。
replace()
方法可用一個新文檔取代當前文檔。
語法
語法
location.assign(URL)
location.reload(forceGet)
參數 | 類型 | 描述 |
---|---|---|
forceGet | Boolean | 可選。如果把該方法的參數設置為 true,那么無論文檔的最后修改日期是什么,它都會繞過緩存,從服務器上重新下載該文檔。 |
location.replace(newURL)