简体   繁体   中英

Passing URL Parameters in href Link

I'm a bit new to this JS stuff and have been surfing and surfing and reading up as much as I can, but I got stumped on this one issue.

I have a website that may contain parameters in the URL. A parameter named “who” to be exact.

If a user comes to the site and their url is http://example.com/?who=123 , I want them to be able to click a href link and their parameter get carried on. So if the link goes to http://anotherexample.com , I'd want the link to contain the user's parameter as well. http://anotherexample.com/?who=123 .

What's the best way to accomplish this? It only needs to be on one of the links, so no concerns about getting the whole site to pass on the parameter.

Thanks!

Would this suffice for you?

Source : https://css-tricks.com/snippets/javascript/get-url-variables/

var svalue=location.search.match(new RegExp("[\?\&]" + "who" + "=([^\&]*)(\&?)","i"));
yourelement.href=yourelement.href+(svalue?svalue[0]:"");

Here is one way you can do it in javascript first when the document loads write a function in your js to get the parameters from the url

function getparms(variable)
{
       let item = window.location.search.substring(1);
       let vars = item.split("&");
       for (let i=0;i< vars.length;i++) {
               let pair = vars[i].split("=");
               if(pair[0] == variable){return pair[1];}
       }
       return(false);
}

This function would return the following from a url

http://www.somesite.com/index.html?who=100&location=2

Calling getparams('who') would return "100"

So you would call it as:

let myParam = getparams('id');

You can build the url in a new function and navigate to it as:

function goToUrl(urlParam){
let hostAddress= 'yourwebsiteaddress';
let url = "http://" + hostAddress "/?=who" + urlParam;

//go to address
window.location.href = url;
}

which would be called as goToUrl(myParam);

*Disclaimer: I wrote this on the fly so it may not be 100% syntactically correct but it should be accurate enough as pseudo code to help you accomplish what you want.

You talked about href , so I assume all links are set with <a> tag.

There are many options to do that, I'll show you the easiest and cleanest one.

So, assuming the current URL is http://www.example.com/?who=123 .

var who = window.location.href.split('?')[1]; // Get `?who=123` from current url
var a = document.getElementsByTagName('a');   // Get all `<a>`
var href;

// Loop through all `<a>`
for (var i = 0; i < a.length; i++){
    // Add `?who=123` to all hrefs found.
    a[i].href += who;
}

You can freely change document.getElementsByTagName('a') to document.getElementById() to suit your needs.

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