BOM 的 location
对象将 URL 解析为独立的片段,可以通过不同的属性访问这些片段。其中 location.search
可以返回 URL 的查询字符串,即从问号开始到 URL 末尾的所有内容,但是没有办法逐个访问其中的每个查询字符串参数。
可以创建一个 getQueryStringArgs()
方法用以解析查询字符串。
function getQueryStringArgs () {
// 取得查询字符串并去掉开头的问号
var qs = (location.search.length > 0 ? location.search.substring(1) : ''),
// 保存数据的对象
args = {},
// 取得每一项
items = qs.length ? qs.split('&') : [],
item = null,
name = null,
value = null,
// for 循环
i = 0,
len = items.length;
// 将每一项添加到变量 args 中
for (i = 0; i < len; ++i) {
item = items[i].split('=');
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if (name.length) {
if (args[name]) {
args[name].push(value);
} else {
args[name] = [value];
}
}
}
return args;
}
函数首先去掉查询字符串开头的问号,并根据 &
符号分割查询字符串,得到 name=value
格式的字符串数组,然后根据 =
符号分割每一项。因为查询字符串应该是被编码过的,所以使用 decodeURIComponent()
方法进行解码。由于每个 name
可能对应多个 value
,所以函数返回的对象的每个属性都为一个字符串数组。