如何在href中使用JavaScript变量?

时间:2021-10-03 09:21:11

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变量的正确方法是什么?

3 个解决方案

#1


7  

This should be what you need.

这应该是你需要的。

var link = "http://www.google.com/";
var a = document.getElementById('yourlinkId');
a.href = link;

#2


1  

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);

#3


-3  

If you're not using jQuery, try this:

如果你不使用jQuery,试试这个:

document.write('<a href="'+variable+'">Link to some site</a>');

#1


7  

This should be what you need.

这应该是你需要的。

var link = "http://www.google.com/";
var a = document.getElementById('yourlinkId');
a.href = link;

#2


1  

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);

#3


-3  

If you're not using jQuery, try this:

如果你不使用jQuery,试试这个:

document.write('<a href="'+variable+'">Link to some site</a>');