本文介绍一种使用 JavaScript 获取 URL 中所有参数键值对的方法。通过解析 window.location.href,将查询字符串按 & 和 = 分割,最终返回包含所有参数及其值的对象或数组。
获取 URL 参数键值对
本文介绍一种利用 JavaScript 获取 URL 中所有参数键值对的方法,供参考。具体实现逻辑如下:
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
希望这段代码对您的 JavaScript 开发有所帮助。