我想将 URL 上的查询字符串附加到页面上的所有锚链接

I want to append the query string on a URL to all anchor links on the page

我正在尝试将 URL 上的查询字符串附加到页面上的所有锚链接。如果页面 URL 是 www.example.com/page?paramter1=variable¶meter2=variable2

变量每次都可能改变,用于分析。

我希望页面上的所有其他链接在页面加载时自动添加 ?paramter1=variable¶meter2=variable2

我一直在玩以下脚本,但我似乎无法通过 URL 中的查询字符串填充变量“myquerystringtoadd”我不一定知道参数是什么,所以它是整个查询字符串。

var querystring = 'myquerystringtoadd';

$('a').each(function()
{
 var href = $(this).attr('href');
 href += (href.match(/\?/) ? '&' : '?') + querystring;
 $(this).attr('href', href);
});

如有任何帮助,我们将不胜感激!

如何在原版 javascript 中使用 querySelectorAll 而不是 jquery。另外,杀死你的领导'?在 querystring。如果您的部分问题涉及如何从当前页面的 url 获取查询字符串,请使用 window.location.search.

在下面的代码段中,您有一些 google 搜索锚点。一个搜索 'x',另一个搜索 'y'。您的查询字符串进一步指定在两个锚点中,您希望安全地搜索图像。

// You will use window.location.search
let querystring = '?tbm=isch&safe=active' 

if(querystring.startsWith('?'))
    querystring = querystring.replace('?', '');

for(let a of document.querySelectorAll('a')) {
    a.href += 
        (a.href.match(/\?/) ? '&' : '?') + 
        querystring;
}
<a href='https://www.google.com/search?q=x'>search x images safely</a><br/>
<a href='https://www.google.com/search?q=y'>search y images safely</a>

注意:您可能已经注意到我经常编辑这个问题,但这只是为了处理 google 查询字符串。