从 url 获取所有参数并插入除一个之外的所有 href
Get all parameters from url and insert on all hrefs except one
朋友们,我需要你们的帮助。我需要从 url
获取参数
ex: www.test.com/?s=1¶m=2¶m=3
并在页面上放入所有 href,减去参数 = s。那么它看起来像这样:
ex: href='www.test.com/?param1¶m=2'
这已经发生了,问题是我不想传递给 hrefs: s 参数
完整代码:
$(document).ready(function() {
function querystringToDict(querystring){
if (querystring.length === 0) {
return {};
}
let queryDict = {}
querystring.split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});
return queryDict;
}
var queryDict = querystringToDict(location.search.substr(1));
var queryHref, queryFinal = {};
var lctSearch = location.search;
$('html a').each(function() {
// if the href contains www.test.com insert params
if ($(this).prop('href').includes('www.test.com')){
if(lctSearch != ''){
param = $(this).attr('href').split('?')[1] === undefined ? '' :
$(this).attr('href').split('?')[1];
queryHref = querystringToDict(param);
queryFinal = Object.assign({}, queryHref, queryDict);
paramFinal = Object.keys(queryFinal).map(key => key + '=' + queryFinal[key]).join('&');
$(this).attr('href',$(this).attr('href').split('?'[0].concat('?',paramFinal));
}
}
});
});
可以在自己写的函数中排除:
querystring
.split("&")
.filter(el => el.split("=")[0] != 's')
// ^^^^^^^^^^^^^^^^^^^^^^^---- exclude the "s" parameter
.forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});
朋友们,我需要你们的帮助。我需要从 url
获取参数ex: www.test.com/?s=1¶m=2¶m=3
并在页面上放入所有 href,减去参数 = s。那么它看起来像这样:
ex: href='www.test.com/?param1¶m=2'
这已经发生了,问题是我不想传递给 hrefs: s 参数
完整代码:
$(document).ready(function() {
function querystringToDict(querystring){
if (querystring.length === 0) {
return {};
}
let queryDict = {}
querystring.split("&").forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});
return queryDict;
}
var queryDict = querystringToDict(location.search.substr(1));
var queryHref, queryFinal = {};
var lctSearch = location.search;
$('html a').each(function() {
// if the href contains www.test.com insert params
if ($(this).prop('href').includes('www.test.com')){
if(lctSearch != ''){
param = $(this).attr('href').split('?')[1] === undefined ? '' :
$(this).attr('href').split('?')[1];
queryHref = querystringToDict(param);
queryFinal = Object.assign({}, queryHref, queryDict);
paramFinal = Object.keys(queryFinal).map(key => key + '=' + queryFinal[key]).join('&');
$(this).attr('href',$(this).attr('href').split('?'[0].concat('?',paramFinal));
}
}
});
});
可以在自己写的函数中排除:
querystring
.split("&")
.filter(el => el.split("=")[0] != 's')
// ^^^^^^^^^^^^^^^^^^^^^^^---- exclude the "s" parameter
.forEach(function(item) {
queryDict[item.split("=")[0]] = item.split("=")[1]
});