简体   繁体   中英

Change a variable in a URL (within HTML) on a Javascript event

I have a Javascript event that is fired when a location is detected. Let's say that the detected location is "Melbourne Australia".

I want to change the following:

<a href="/search?location=&input=Suits">Suits</a> 

To be:

<a href="/search?location=Melbourne Australia&input=Suits">Suits</a> 

All I can think of us changing the entire href value. Is there a 'sane' way to change only the value of location= when the event is fired.

give a id to your link

<a href="/search?location=&input=Suits" id="my_link">Suits</a> 

and use js to modify it

var your_location = "Melbourne Australia"; // can be dynamic

var obj = document.getElementById('my_link');

var h = obj.href;

var string_to_find = "location=";
var string_to_replace = "location="+your_location;
var new_h = h.replace(string_to_find, string_to_replace);

obj.href=new_h;

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