2011-08-20 113 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/