【JavaScript编程】window.location.search 返回值为空


一、Location 对象


window.location 对象用于获得当前页面的地址 (URL),并把浏览器重定向到新的页面。


二、属性hash和search的区别


属性描述
location.hash设置或返回一个URL的锚部分(从 # 号开始的部分)。
location.search设置或返回一个URL的查询部分(从 ? 开始的部分)。

1、示例1,url中#?后面: https://blog.csdn.net/article?id=94458654#first

属性结果
location.hash'#first'
location.search'?id=94458654'注意:不包含#后面的内容

2、示例2,url中#?前面: https://blog.csdn.net/article#first?id=94458654

属性结果
location.hash'#first?id=94458654'注意:包含?后面的内容
location.search''值为空

三、为什么 location.search 会为空


在「示例2」中,因为?id=94458654是属于location.hash的内容,可以理解为这一部分内容先被location.hash取走了,location.search再取值就取不到了。


四、解决


/**
 * @description 获取url参数
 * @param {String} name 参数名,不传则返回所有参数的对象
 * @return {String Object}
 */
function getParams(name) {
    var search = window.location.search.substring(1)
    if (!search) {
        search = window.location.hash.split('?')[1]
    }
    if (search) {
        var obj = JSON.parse('{"' + decodeURIComponent(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
        return name ? obj[name] : obj
    }
}

以上示例调用结果:

getParams() // 返回:{id: '94458654'}
getParams('id') // 返回:'94458654'

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值