提问者:小点点

如何使用jQuery查询url参数? [副本]


我想使用query查询URL中的参数。

假设我的访问者打开urlexample.com/#o-12345

这里#o是标识符/参数,12345是ID。

如何使用jQuery检查URL中是否存在特定参数,以及如何提取ID?


共1个答案

匿名用户

这里我编写了一个解析器,它将所有参数存储到一个对象中:

let params = {};
let splittedUrl = window.location.href.split('#');
if (splittedUrl.length >= 1) {
  splittedUrl[1].split('&').forEach(elm=>{
    if (elm != '') {
      let spl = elm.split('-');
      params[spl[0]] = (spl.length >= 2 ? spl[1] : true);
    }
  });
}

(此代码还允许您添加更多带有ampercent符号的参数。)

示例(URL为“https://Example.com/#foo-bar&tmp-qux”):

params.length // 2
params['foo'] // bar
params['tmp'] // qux

我知道,您要求使用jQuery,但我认为纯JavaScript也应该可以:)