简体   繁体   中英

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

I am trying to append a query string on a URL to all anchor links on page. If the page URL was www.example.com/page?paramter1=variable&parameter2=variable2

The variables may change each time and it is to be used for analytics.

I would like all the other links on the page to automatically get ?paramter1=variable&parameter2=variable2 added to them when the page loads.

I had been playing around with the following script but i can't seem get variable ' myquerystringtoadd ' to be populated by the query string in the URL which I don't necessarily know what the parameters would be so it is the whole query string.

var querystring = 'myquerystringtoadd';

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

Any help would be much appreciated!

How about using querySelectorAll in vanilla javascript instead of jquery. Also, kill your leading '?' in querystring . And if part of your question involves how to get the querystring from the current page's url, use window.location.search .

In the snippet below, you have some google search anchors. One searches 'x', and the other searches 'y'. Your query string further specifies that in both anchors, you want a safe search for images.

 // 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>

Note: You may have noticed that I'm editing this question a lot, but it's just to to work with google query strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM