window.location和document.location的區(qū)別分析
2024-05-06 14:16:24
供稿:網(wǎng)友
document.location 這個(gè)對(duì)象包含了當(dāng)前URL的信息
location.host 獲取port號(hào)
location.hostname 設(shè)置或獲取主機(jī)名稱
location.href 設(shè)置或獲取整個(gè)URL
location.port設(shè)置或獲取URL的端口號(hào)
location.search 設(shè)置或獲取href屬性中跟在問(wèn)號(hào)后面的部分
-------------------------------------------------------------------------------
js中window.location的應(yīng)用
URL即:統(tǒng)一資源定位符 (Uniform Resource Locator, URL)
完整的URL由這幾個(gè)部分構(gòu)成:
scheme://host:port/path?query#fragment
scheme:通信協(xié)議
常用的http,ftp,maito等
host:主機(jī)
服務(wù)器(計(jì)算機(jī))域名系統(tǒng) (DNS) 主機(jī)名或 IP 地址。
port:端口號(hào)
整數(shù),可選,省略時(shí)使用方案的默認(rèn)端口,如http的默認(rèn)端口為80。
path:路徑
由零或多個(gè)"/"符號(hào)隔開的字符串,一般用來(lái)表示主機(jī)上的一個(gè)目錄或文件地址。
query:查詢
可選,用于給動(dòng)態(tài)網(wǎng)頁(yè)(如使用CGI、ISAPI、PHP/JSP/ASP/ASP.NET等技術(shù)制作的網(wǎng)頁(yè))傳遞參數(shù),可有多個(gè)參數(shù),用"&"符號(hào)隔開,每個(gè)參數(shù)的名和值用"="符號(hào)隔開。
fragment:信息片斷
字符串,用于指定網(wǎng)絡(luò)資源中的片斷。例如一個(gè)網(wǎng)頁(yè)中有多個(gè)名詞解釋,可使用fragment直接定位到某一名詞解釋。(也稱為錨點(diǎn).)
對(duì)于這樣一個(gè)URL
http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere
我們可以用javascript獲得其中的各個(gè)部分
1, window.location.href
整個(gè)URl字符串(在瀏覽器中就是完整的地址欄)
本例返回值: http://www.x2y2.com:80/fisker/post/0703/window.location.html?ver=1.0&id=6#imhere
2,window.location.protocol
URL 的協(xié)議部分
本例返回值:http:
3,window.location.host
URL 的主機(jī)部分
本例返回值:www.x2y2.com
4,window.location.port
URL 的端口部分
如果采用默認(rèn)的80端口(update:即使添加了:80),那么返回值并不是默認(rèn)的80而是空字符
本例返回值:""
5,window.location.pathname
URL 的路徑部分(就是文件地址)
本例返回值:/fisker/post/0703/window.location.html
6,window.location.search
查詢(參數(shù))部分
除了給動(dòng)態(tài)語(yǔ)言賦值以外,我們同樣可以給靜態(tài)頁(yè)面,并使用javascript來(lái)獲得相信應(yīng)的參數(shù)值
本例返回值:?ver=1.0&id=6
7,window.location.hash
錨點(diǎn)==========================================
document.href="http://m.survivalescaperooms.com"
document.location="http://m.survivalescaperooms.com"
window.location="http://m.survivalescaperooms.com"
只是屬于包含的問(wèn)題
一個(gè)是window,一個(gè)是document
location 是個(gè)對(duì)象 比如本頁(yè)的document.location 和window.location的屬性有
location.hostname = community.csdn.net
location.href = http://community.csdn.net/Expert/topic/4033/4033372.xml?temp=2.695864E-02
location.host = community.csdn.net
location.hash =
location.port =
location.pathname = /Expert/topic/4033/4033372.xml
location.search = ?temp=2.695864E-02