使用Javascript将URL参数传递给href链接 [英] Passing an URL parameter to a href link using Javascript
本文介绍了使用Javascript将URL参数传递给href链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码用于将URL参数传递给表单标记:
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>
并且......
<body onload="onLoad()">
<!-- your form and hidden field goes here -->
<input type="hidden" name="your-field" id="your-field" />
如何将相同的值传递给HTML链接,以便最终结果为:
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]" >
其中[ID]是将参数添加到链接所需的任何代码段?
Where [ID] is the whatever piece of code that is needed to add the parameter to the link?
提前致谢。
推荐答案
你应该给一个id你链接,像这样:
You should give an id to you link, like this:
<a id="YOUR_ID" href="#" >
然后你有两种方法可以解决问题,使用纯Javascript或使用jQuery:
And then you have two ways to solve the problem, use pure Javascript or use jQuery:
如果您使用jquery,您可以使用onLoad函数并在内部注入以下内容:
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使用纯javascript:
OR using pure javascript:
var url = "http://www.mysite.com?source=" + value;
var element = document.getElementById('YOUR_ID');
element.setAttribute("href",url)
这篇关于使用Javascript将URL参数传递给href链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文