location 对象是很特别的一个对象, 因为它既是 window 对象的属性, 也是 document 对象的属性. 换句话说, window.location 和 document.location 引用的是同一个对象. 这里我们就简单的介绍一下 location 处理 URL 片段的方法吧!
一,
如下每个属性前省去 location 前缀:
hash '#xxxxx'返回 URL 中的 hash(即 #号后面的字符)
host'www.baidu.com:80'返回服务器名称和端口号
hostname 'www.baidu.com'返回不带端口号的服务器名称
href'http:www.baidu.com'返回当前加载页面的完整 URL, 而 location 对象的 toString()方法也返回这个值.
path'8080'返回当前 URL 的指定的端口号
pathname'/xxxx/sssss/'返回 URL 中的目录和 (或) 文件名
portocol(协议)'http:'返回页面使用的协议 http: 或 https:
search '?q=test01'返回 URL 的查询字符串. 这个字符串以问号开头
二,
URL 查询字符串参数:
1. 获取 search
- function getQueryStringArgs () {
- // 获取查询字符并去掉开头的问号
- var searchStr = location.search.length> 0 ? location.search.substring(1) : '',
- // 保存数据的对象
- args = {},
- // 获取每一项参数
- tems = searchStr.length ? searchStr.split('&') : [],
- item = null,
- name = null,
- value = null,
- i = 0,
- len = items.length;
- // 逐个将每一项添加到 args 对象中
- for (i = 0; i < len; i++) {
- item = items[i].split('=');
- name = decodeURLComponent(item[0]);
- value = decodeURLComponent(item[1]);
- if (name.length) {
- args[name] = value
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2760541.html