如何将url参数传递/附加到页面上的所有href(链接)



使用javascript,我的目标是查询URL并将参数附加到页面上的所有链接。如果链接已经包含一个参数,链接将附加新的参数:

用户访问页面:https://example.com/?location=brazil
页面上的链接为:https://link.com/?hello=ok
链接变为:https://link.com/?hello=ok&location=巴西

如果链接上没有以前的参数,则变为:
https://link.com/?location=brazil

我尝试了以下代码:

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
var current = link.href;
link.href = current + queryString;
});
</script>

但是,当链接已经包含参数时,它会使用而不是&所以它变成:

https://link.com/?hello=ok?location=brazil

我该如何解决这个问题?

您可以检查queryString变量是否包含?,并将其替换为&

所以你的代码应该是类似的

var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
var current = link.href;
const queryStrToUse = queryString.replace('?', '&')
link.href = current + queryStrToUse;
});

使用javascript更改锚点href属性不是一个好主意,原因有很多,但如果这是必须的,您可以这样做:

document.querySelectorAll("a").forEach(link => {
link.href = link.href.includes("?") ? link.href + queryString.replace("?", "&") : link.href + queryString; });
var queryString = new URL(window.location).search;
document.querySelectorAll("[href]").forEach(link => {
var current = link.href;
link.href = `${current}${current.includes('?') ? queryString.replace('?', '&') : queryString}`;
});

最新更新