简体   繁体   English

在Javascript事件上更改URL(在HTML中)中的变量

[英]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. 我有一个在检测到位置时触发的Javascript事件。 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. 我只能想到我们改变整个href值。 Is there a 'sane' way to change only the value of location= when the event is fired. 当事件被触发时,是否有一种“理智”的方式来仅改变location=的值。

give a id to your link 给你的链接一个id

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

and use js to modify it 并使用js来修改它

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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