平时我们做项目的时候经常需要截取 url地址中的参数。
比如:https://www.baidu.com/s?ie=UTF-8&name=小茴香&age=18
来个方法:
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);
}
console.log(getQueryVariable('aa'));
console.log(getQueryVariable('bb'));
举个例子:url为:http://127.0.0.1:5501/test.html?aa=11&bb=2222
那么,但你用上面的方法去调用:
console.log(getQueryVariable('aa')); //11
console.log(getQueryVariable('bb')); //222
如果没有参数则为 false