简体   繁体   中英

Passing an URL parameter to a href link using Javascript

I have the following code working to pass a URL parameter to a form tag:

<script type="text/javascript">
  function getQueryVariable(variable) { 
 var query = window.location.search.substring(1); 
 var vars = query.split("&"); 
 for (var i=0;i<vars.length;i++) { 
 var pair = vars[i].split("="); 
 if (pair[0] == variable) { 
   return pair[1]; 
    }
  }
}
 function onLoad() {
var value = getQueryVariable("ID");
var e = document.getElementById('your-field');
e.value = value;
}
</script>

And...

<body onload="onLoad()">
 <!-- your form and hidden field goes here -->
 <input type="hidden" name="your-field" id="your-field" />

How can I pass the same value to an HTML link so that the end result would be:

<a href="http://www.mysite.com?source=[ID]" >

Where [ID] is the whatever piece of code that is needed to add the parameter to the link?

Thanks in advance.

You should give an id to you link, like this:

<a id="YOUR_ID" href="#" >

And then you have two ways to solve the problem, use pure Javascript or use jQuery:

IF you use jquery you can use your onLoad function and inside inject the following:

var url = "http://www.mysite.com?source=" + value;
$("#YOUR_ID").attr("href",url)

OR using pure javascript:

var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_ID');
element.setAttribute("href",url)

Change the function onload to this:

function onLoad() {
   var value = getQueryVariable("ID");
   var e = document.getElementById('your-field');
   e.value = value;

   var url = "http://www.mysite.com?source=" + value;
   var element = document.getElementById('YOUR_<A>_ELEMENT_ID');
   element.setAttribute("href",url)
}

I'm using the piece of code that Joao Almeida suggested so his example using jQuery works good too.

Good Luck!

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