JavaScript获取URL中参数的值
程序员文章站
2024-02-18 09:06:40
...
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
//获取url中的参数
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); //匹配目标参数
if (r != null)
return unescape(r[2]);
return null; //返回参数值
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
function fun() {
var param1 = getQueryVariable("param1");
console.info(param1);
var param2 = getQueryVariable("param2");
console.info(param2);
var param3 = getUrlParam("param3");
console.info(param3);
var param4 = getUrlParam("param4");
console.info(param4);
}
</script>
</head>
<body>
<button onclick="fun()">Button</button>
</body>
</html>
测试url:demo.html?param1=1234¶m2=中国¶m3=abcd¶m=asdf
结果:
上一篇: MUI 页面传递参数(父传子)