为什么 window.location.search 为空?

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:当前页面的完整URLhttp://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.应用

//获取url参数
function GetQueryString (name)
{
    var after = window.location.hash.split("?")[1];
    if(after)
    {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = after.match(reg);
        if(r != null)
        {
            return  decodeURIComponent(r[2]);
        }
        else
        {
            return null;
        }
    }
}

原文地址:http://www.cnblogs.com/codebook/p/5918079.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值