? location
接口包含著當(dāng)前URL上的信息,Document
和 Window
接口都有這樣一個(gè)鏈接的Location,分別通過(guò) Document.location
和Window.location
訪問(wèn)
? 為了方便本文的描述,假定現(xiàn)有URL:
? http://example.com:1234/test.html?user=zfs&hobby=travel#part2
# location對(duì)象屬性
- location.href
? href
是一個(gè)可讀可寫(xiě)的字符串。可以通過(guò)其設(shè)置新的鏈接地址,也可獲取現(xiàn)URL上的信息。
console.log(window.location.href)
// http://example.com:1234/test.html?user=zfs&hobby=travel#part2
?
- location.search
? search
是一個(gè)可讀可寫(xiě)的屬性,讀取時(shí)返回的是當(dāng)前URL的查詢部分,包括?
號(hào)。
【注意】截取內(nèi)容不包含錨點(diǎn)信息
// set
location.search= URL
// get
console.log(window.location.search) // '?user=zfs&hobby=travel'
?
- location.hash
? hash
是一個(gè)可讀可寫(xiě)的字符串,讀取時(shí)返回的是 URL 的錨部分,包括#
號(hào)
【注意】對(duì)于當(dāng)前流行的Vue項(xiàng)目,如果使用的hash路由,那么參數(shù)(search
)部分也將被當(dāng)做hash來(lái)看待
// set
location.hash=anchorname
// get
console.log(location.hash) // '#part2'
vue中的hash路由模式,假設(shè)url:
https://example:1234/index.html#/personal?user=zfs&hobby=traval
console.log(window.location.hash) // '#/personal?user=zfs&hobby=traval'
?
- location.host
? host
是個(gè)可讀可寫(xiě)的屬性,可設(shè)置或返回當(dāng)前URL的主機(jī)名稱和端口號(hào)
// set
location.host = host
// get
console.log(location.host) // 'example.com:1234'
?
- location.hostname
? hostname
是個(gè)可讀可寫(xiě)的屬性,可設(shè)置或返回當(dāng)前URL的主機(jī)名稱
// set
location.hostname = hostname
// get
console.log(location.hostname) // 'example.com'
?
- location.port
? 可讀可寫(xiě),設(shè)置或返回當(dāng)前主機(jī)服務(wù)端口
// set
location.port = portnumber
// get
console.log(location.port) // '1234'
?
- location.pathname
? 可讀可寫(xiě),設(shè)置或返回當(dāng)前URL路徑部分
// set
location.pathname = path
// get
console.log(location.pathname) // '/index.html'
?
- location.protocol
? 可讀可寫(xiě),設(shè)置或返回當(dāng)前URL中的協(xié)議
// set
location.protocol = path
// get
console.log(location.protocol) // http:
?
# location 對(duì)象方法
- assign()
? assign()可以載入一個(gè)新的文檔頁(yè)面
window.location.assign("http://example.com")
?
- reload()
? 重新載入當(dāng)前文檔頁(yè)面。該方法可以接受一個(gè)可選的Boolean
類型參數(shù)。
? 當(dāng)為false
時(shí),它就會(huì)用 HTTP 頭 If-Modified-Since 來(lái)檢測(cè)服務(wù)器上的文檔是否已改變。如果已改變,則再次下載,否則將從緩存中裝載該文檔。
? 當(dāng)為true
時(shí),那么無(wú)論文檔的最后修改日期是什么,它都會(huì)繞過(guò)緩存,從服務(wù)器上重新下載該文檔。
window.location.reload(true)
?
- replace()
? 用一個(gè)新文檔取代當(dāng)前文檔,并且不會(huì)在History對(duì)象中生成一條新的記錄,將用新的URL覆蓋當(dāng)前URL
window.location.replace("http://example.com")
?
# 完整案例
var url = document.createElement('a');
url.;
console.log(url.href); // https://developer.mozilla.org/en-US/search?q=URL#search-results
console.log(url.protocol); // https:
console.log(url.host); // developer.mozilla.org
console.log(url.hostname); // developer.mozilla.org
console.log(url.port); // (blank - https assumes port 443)
console.log(url.pathname); // /en-US/search
console.log(url.search); // ?q=URL
console.log(url.hash); // #search-results-close-container
console.log(url.origin); // https://developer.mozilla.org