为什么 window.location.search 为空?

简介: 1,什么是window.location?示例URL:http://b.a.com:88/index.php?name=kang&when=2011#first属性含义值protocol:协议"http:"hostname:服务器的名字"b.

1,什么是window.location?示例

URL:http://b.a.com:88/index.php?name=kang&when=2011#first

属性 含义
protocol: 协议 "http:"
hostname: 服务器的名字 "b.a.com"
port: 端口 "88"
pathname: URL中主机名后的部分 "/index.php"
search: "?"后的部分,又称为查询字符串 "?name=kang&when=2011"
hash: 返回"#"之后的内容 "#first"
host: 等于hostname + port "b.a.com:88"
href: 当前页面的完整URL "http://www.a.com:88/index.php?name=kang&when=2011#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=2011#first

search:"?name=kang&how="     第一个"?"之后 ( 经测试应该是:第一个"?"之后 , #之前)
hash:"#when=2011#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 //获取url参数
 2 function GetQueryString (name)
 3 {
 4     var after = window.location.hash.split("?")[1];
 5     if(after)
 6     {
 7         var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
 8         var r = after.match(reg);
 9         if(r != null)
10         {
11             return  decodeURIComponent(r[2]);
12         }
13         else
14         {
15             return null;
16         }
17     }
18 }

目录
相关文章
|
4天前
|
JavaScript 前端开发
location.href和 window.location的区别有这些!
location.href和 window.location的区别有这些!
|
5月前
window.location对象使用
window.location对象使用
26 0
|
10月前
|
存储 算法 API
|
前端开发
location.href与window.open()的用法与区别,你都知道吗?
通常在Web开发中,打开一个页面有两种方式,一种是使用location的href属性来打开一个页面;还有一种就是使用window对象下的open()方法。
588 0
location.href与window.open()的用法与区别,你都知道吗?
|
Linux
解决办法:error: <item> inner element must either be a resource reference or empty.
解决办法:error: <item> inner element must either be a resource reference or empty.
210 0
|
移动开发 Android开发
解决移动端页面window.location.replace不生效的问题
解决移动端页面window.location.replace不生效的问题
1481 0
|
Web App开发 安全
Not allowed to navigate top frame to data URL
Not allowed to navigate top frame to data URL
269 0
|
Web App开发 JavaScript 前端开发

热门文章

最新文章