【发布时间】:2020-10-14 14:55:55
【问题描述】:
我想用query来查询URL中的参数。
假设我的访客打开网址example.com/#o-12345
这里#o 是标识符/参数,12345 是 ID。
如何使用 jQuery 检查 URL 中是否存在特定参数以及如何提取 ID?
【问题讨论】:
我想用query来查询URL中的参数。
假设我的访客打开网址example.com/#o-12345
这里#o 是标识符/参数,12345 是 ID。
如何使用 jQuery 检查 URL 中是否存在特定参数以及如何提取 ID?
【问题讨论】:
这里我写了一个解析器,它将你所有的参数存储到一个对象中:
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);
}
});
}
(此代码还可以让您添加更多带有电流符号的参数。)
示例(使用 URL 'https://example.com/#foo-bar&tmp-qux'):
Object.keys(params).length // 2
params['foo'] // bar
params['tmp'] // qux
我知道,您要求使用 jQuery,但我认为纯 JavaScript 也应该可以工作 :)
【讨论】: