简体   繁体   English

使用JavaScript将字符串注入href中?

[英]Inject string into a href with javascript?

In the same way that I can inject some text into a div with javascript, how can I inject a string into the href portion of an html anchor? 以与我可以使用javascript将一些文本注入div的方式相同,如何将字符串注入html锚的href部分?

var div = document.getElementById('hrefId');
div.innerHTML = "Some dandy text!";

Something like this? 像这样吗

var hrefVar = document.getElementById('hrefId');
hrefVar.innerHTML = "Some dandy text!";

The problem is that it populates the space between <a></a> , as opposed to filling up the href with text, which is what I need to get the link to work. 问题在于,它填充了<a></a>之间的空间,而不是用文本填充href,这是使链接正常工作所需要的。

<a href="" id="href"></a>

Solution: 解:

var hrefVar = document.getElementById('hrefId');
hrefVar.href = "http://www.microsoft.com/";

Since this was never officially answered I'll post it here. 由于从未得到正式答复,因此我将其张贴在这里。

Todo this with pure javascript : 使用纯javascript做到这一点:

var hrefVar = document.getElementById('hrefId');
hrefVar.href = "http://www.microsoft.com/";

Or could do it in one line 或者可以一行完成

var hrefVar = document.getElementById('hrefId').href="http://www.microsoft.com/";

jQuery : jQuery的

$("#hrefId").attr("href","http://www.microsoft.com/");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM