如何在 href 中使用 JavaScript 变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11174412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use a JavaScript variable in a href?
提问by BRAINBUZZ media
I have a JavaScript variable I grabbed from a form field and I am trying to use it for the href = value
in a link. What is the proper way to output this JavaScript variable in HTML?
我有一个从表单字段中获取的 JavaScript 变量,我试图将它用于href = value
链接中。在 HTML 中输出这个 JavaScript 变量的正确方法是什么?
回答by Josh Mein
This should be what you need.
这应该是你需要的。
var link = "http://www.google.com/";
var a = document.getElementById('yourlinkId');
a.href = link;
回答by Gregg
Update the href value via javascript. Using something like jQuery it is as simple as:
通过 javascript 更新 href 值。使用类似 jQuery 的东西就像这样简单:
var link = "www.google.com";
$("a").attr("href", link);
回答by Kyle
If you're not using jQuery, try this:
如果您不使用 jQuery,请尝试以下操作:
document.write('<a href="'+variable+'">Link to some site</a>');