最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add a var to href- Stack Overflow

programmeradmin3浏览0评论

I need something like this:

var link = " ";

<a href='link' />

So I need to use a variable as href attribue of a link. Is this possible?

It worked with "<a href= '" + link + "' />". Is there a better way?

I need something like this:

var link = " http://www.google.";

<a href='link' />

So I need to use a variable as href attribue of a link. Is this possible?

It worked with "<a href= '" + link + "' />". Is there a better way?

Share Improve this question edited Jun 2, 2012 at 23:22 Wladimir Palant 57.7k12 gold badges99 silver badges127 bronze badges asked Jan 23, 2010 at 0:31 msheshtawymsheshtawy 4154 gold badges12 silver badges17 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

You should set the href value on the server, it is bad design to use scripting for this.

However, to answer the question, it can be done by using script to set the href property of the A element once it is in the DOM, e.g.:

<a href="<a useful URI if javascript not available>" id="a0">foo</a>

<script type="text/javascript">
  var a = document.getElementById('a0');
  if (a) {
    a.href = "http://www.google.";
  }
</script>

Of course there are a thousand other ways, all with their pitfalls. So set the value on the server and avoid them all.

-- 
Rob

Using jQuery this would be

var link = "http://www.google.";
$("a[href='link']").attr("href", link);

Though this would not degrade gracefully should javascript be turned off and you'd probably want to use something else rather than selecting by the href anyways.

If you are actually writing both of those lines of code, it would be much easier to use write

<a href="http://www.google.">Google</a>

Otherwise, you will need to use JavaScript to set the href property of your link, which will require getting a reference to it (which means you should set its id property).

So you could write something like:

<a id="myLink">Google</a>

and in your JavaScript have:

document.getElementById("myLink").href=link

but first, please think about whether this is really necessary (or provide some more details in your question).

You're using Jetpack, so you can do <a href={link}/>.toXMLString().

If all you want to do is create an <a/> element, use the following.

var anchor = document.createElement("a");
anchor.href = link;
发布评论

评论列表(0)

  1. 暂无评论