1,什么是window.location?示例
URL:http://b.a.com:88/index.php?name=kang&when=2016#first
| 屬性 | 含義 | 值 |
|---|---|---|
| protocol: | 協議 | "http:" |
| hostname: | 服務器的名字 | "b.a.com" |
| port: | 端口 | "88" |
| pathname: | URL中主機名后的部分 | "/index.php" |
| search: | "?"后的部分,又稱為查詢字符串 | "?name=kang&when=2016" |
| hash: | 返回"#"之后的內容 | "#first" |
| host: | 等於hostname + port | "b.a.com:88" |
| href: | 當前頁面的完整URL | "http://www.a.com:88/index.php?name=kang&when=2016#first" |
window.location和document.location互相等價的,可以交換使用
location的8個屬性都是可讀寫的,但是只有href與hash的寫才有意義。例如改變location.href會重新定位到一個URL,而修改location.hash會跳到當前頁面中的anchor(<a id="name">或者<div id="id">等)名字的標記(如果有),而且頁面不會被重新加載
注意
URL:http://b.a.com:88/index.php?name=kang&how=#when=2016#first
hash:"#when=2016#first" 第一個"#"之后的內容
2,為什么 window.location.search 為空?
答:注意上面的search和hash的區別,如果URL中“?”之前有一個“#”比如:“http://localhost:63342/index.html#/version?type=35&id=5”那么使用window.location.search得到的就是空(“”)。因為“?type=35&id=5”串字符是屬於“#/version?type=35&id=5”這個串字符的,也就是說查詢字符串search只能在取到“?”后面和“#”之前的內容,如果“#”之前沒有“?”search取值為空。
3,應用
1 /** 2 * 解析URL傳參 3 * @param {Object} key 4 */ 5 6 function getQueryString(key) 7 { 8 var after = window.location.search; 9 if(after.indexOf('?') === -1) return null; //如果url中沒有傳參直接返回空 10 11 //key存在先通過search取值如果取不到就通過hash來取 12 after = after.substr(1) || window.location.hash.split("?")[1]; 13 14 if(after) 15 { 16 var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)"); 17 var r = after.match(reg); 18 if(r != null) 19 { 20 return decodeURIComponent(r[2]); 21 } 22 else 23 { 24 return null; 25 } 26 } 27 }
