location是常用的一个对象,提供了与当前窗口中加载的文档有关的信息,包含了完整了URL。接下来我们看看如何查询URL中的字符串参数:
function getQueryStringArgs() {
//取得查询字符串去掉开头?的信息
var qs = (location.length > 0 ? location.search.substring(1) : ''),
//保存查询参数的对象
args = {},
//取得每一项
items = qs.length ? qs.split('&') : [],
item = null,
name = null,
value = null,
//在for循环中使用
i = 0,
len = items.length;
//遍历每一项添加到agrs中
for(i = 0; i < len; i++) {
item = items[i].split('=');
name = decodeURIComponent(item[0]);
value = decodeURIComponent(item[1]);
if(name.length) {
args[name] = value;
}
}
return args;
}
//假设要查询的字符串是?id=12&address=guangzhou
var args = getQueryStringArgs();
alert(args['id']); //'12'
alert(args['address']); //'guangzhou'
本文介绍了一个JavaScript函数,用于从浏览器地址栏的URL中提取查询字符串参数,并将其解析为一个易于访问的对象。
986

被折叠的 条评论
为什么被折叠?



