网站首页 > 基础教程 正文
进入我的主页,查看更多JS的分享!
我的代码有多短,本文章就有多短!(_)
1. 思路
先获取浏览器参数的字符串,判断并转为对象,如果没有指定参数名,直接返回该对象。
2. 代码
需要说的话都在注释里了,先贴上代码(好像明白了程序员为啥话不多)
/**
* 获取:当前链接的参数
* 若不指定参数,则以对象的形式返回全部参数
* 若指定参数名,则只返回对应的值
* 处理:中文解码
* 测试:"?id=123&name=哈哈哈"
* 结果:{id: "123", name: "哈哈哈"}
*/
var getLocationParam = (name) = >{
let param = window.location.search.substr(1);
if (!param) {
return undefined;
} else {
let pArr = param.split("&");
let res = {};
for (let i = 0; i < pArr.length; i++) {
let item = pArr[i].split("=");
res[item[0]] = item[1] ? decodeURI(item[1]) : null;
}
return !name ? res: res[name];
}
};
如果参数有中文,直接用"decodeURI()",而"unescape()"并不适用。(测试了QQBrowser、Chrome、IE9-11)
运行:
console.log(getLocationParam("id"));
//输出:123
console.log(getLocationParam("name"));
//输出:哈哈哈
console.log(getLocationParam("due"));
//输出:undefined
console.log(getLocationParam());
//输出:{id: "123", name: "哈哈哈"}
网上有一段代码,是用正则来获取指定的参数,虽然只能获取指定的参数。嘛,直接贴上代码看看吧:
/**
* 获取:当前链接的指定的参数
* 方法:采用正则
*/
var getLocationQueryByName = (name) = >{
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return decodeURI(r[2]);
return null;
};
猜你喜欢
- 2025-05-28 只有手机号也能定位?那手机号怎么定位呢?
- 2025-05-28 Spring Cloud Config Server目录遍历漏洞分析 (CVE-2020-5410)
- 2025-05-28 重置Win10所有原生应用
- 2025-05-28 图文教程:Win10应用加载失败问题的解决方法
- 2025-05-28 浏览器开不了网页?全套解决方案留在这儿
- 2025-05-28 app 的后台权限到底对应了什么?教你重新认识这 11 个权限保护隐私
- 2025-05-28 查漏补缺!我再讲一遍Nginx,务必记住这10000字内容
- 2025-05-28 fake location使用详解
- 2025-05-28 Python 查看微信撤回的消息(完整代码)
- 2025-05-28 代理式AI的综合教程:从基础快速响应到全自主代码生成与执行
- 最近发表
- 标签列表
-
- jsp (69)
- gitpush (78)
- gitreset (66)
- python字典 (67)
- dockercp (63)
- gitclone命令 (63)
- dockersave (62)
- linux命令大全 (65)
- pythonif (86)
- location.href (69)
- dockerexec (65)
- tail-f (79)
- queryselectorall (63)
- location.search (79)
- bootstrap教程 (74)
- deletesql (62)
- linuxgzip (68)
- 字符串连接 (73)
- html标签 (69)
- c++初始化列表 (64)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)