window.location属性用法及解决一个window.location.search为什么为空的问题

  通常用window.location该属性获取页面 URL 地址:

1、什么是window.location?

  比如URL:http://b.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、JS 脚本捕获页面 GET 方式请求的参数?

  其实直接使用 window.location.search 获得,然后通过 split 方法结合循环遍历自由组织数据格式。大概处理如下:

var searchURL = window.location.search;
searchURL = searchURL.substring(1, searchURL.length);
var targetPageId = searchURL.split("&")[0].split("=")[1];
原文地址:https://www.cnblogs.com/goloving/p/9292192.html