2011-08-20 80 views
0

我试图在下面使用Javascript添加一段文本的链接。请帮忙。范围内的JavaScript链接

<div id="features"> 
<h2>Features</h2> 
<div id="emma2011_left"> 
<h2>Image of the Day</h2> 
<div id="dImg"> 
<div id="dailyimg" class="feature"></div> 
<div id="title" class="feature"></div> 
<div id="caption" class="feature"></div><br /> 
<span id="span" class="feature"><a id="pidlink">Link to the object</a></span> 
</div> 
</div> 


<script type="text/javascript"> 

... 
link = document.createElement("a"); 
link.setAttribute("href", "http://abc.org/index.aspx?objectid=" + oTodayImage.pid); 
var span = document.createElement("span"); 
var txt = link.href; 
var textNode = document.createTextNode(txt); 
span.appendChild(textNode); 
</script> 
+1

所以什么错? –

+0

链接没有显示,我不知道我在做什么错 – multiv123

+2

那是因为你永远不会追加任何链接。 –

回答

0

使用jQuery的append

var href = "http://abc.org/index.aspx?objectid=" + oTodayImage.pid; 
$('#span').append("<a href='" + href + "'>test</a>") ; 
2

你错过了一步。您将textnode添加到跨度而不是链接。那么你应该已经把链接到跨度中......

var link = document.createElement("a"); 
link.setAttribute("href", "http://www.google.com"); 

var span = document.createElement("span"); 
var txt = link.href; 
var textNode = document.createTextNode(txt); 
link.appendChild(textNode); 
span.appendChild(link); 


//example of setting the link into a div on the page... 
document.getElementById("div").appendChild(span); 
+0

我试过这段代码,但超链接似乎没有出现。 – multiv123

+0

你需要设置'link''的innerHTML'属性,检查出编辑。 – Rafay

+1

。我的原始代码只是为了修复跨度的创建...你仍然需要把它放在某处... – gislikonrad

1

而不是创造,你还可以设置链接的innerHTML文本节点。最后在创建这个span后,您需要将其附加到某个容器中,现在我已将其附加到body

工作demo

var link = document.createElement("a"); 
//here in the attribute value I have harded objectid=1 for testing 
//replace it by your code to get the id and append it 
link.setAttribute("href", "http://abc.org/index.aspx?objectid=1"); 
link.innerHTML = "Link to the object"; 
var span = document.createElement("span"); 
span.appendChild(link); 
document.body.appendChild(span); 
+0

@ multiv123 - 看看这个解决方案。 – ShankarSangoli

+0

我试过这个,但url本身没有附加到链接,很奇怪 – multiv123

+0

它工作得很好。你可以看看小提琴演示。 – ShankarSangoli

1
(function() { 
    var _a, _div, _span; 

    _span = document.createElement("span"); 
    _a = document.createElement("a"); 
    _div = (document.getElementsByTagName("div"))[0]; 

    _a.setAttribute("href", "http://abc.org/index.aspx?objectid="); 
    _a.innerHTML = "Link to the object"; 

    _span.appendChild(_a); 
    _div.appendChild(_span); 
}).call(this); 
  1. 得到div元素使用一些方法;
  2. 必须将span扩展到div元素以显示所有元素。

例如:http://jsfiddle.net/bz6bu/