zoukankan      html  css  js  c++  java
  • 为什么 window.location.search 为空?

    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

    search:"?name=kang&how="     第一个"?"之后
    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     }
  • 相关阅读:
    用户及文件权限管理
    Linux基础操作及概念
    监督学习和非监督学习
    基于仿生算法的智能系统I
    9.Dijkstra求最短路 II 堆优化的Dijkstra
    8.Dijkstra求最短路 I 朴素Dijkstra
    7.有向图的拓扑序列 拓扑排序
    6.树与图的广度优先遍历 图中点的层次
    5.树的重心 树与图的深度优先遍历
    4.八数码 BFS
  • 原文地址:https://www.cnblogs.com/codebook/p/5918079.html
Copyright © 2011-2022 走看看