跨越内部的JavaScript链接

时间:2011-08-20 23:20:22

标签: javascript jquery

我正在尝试使用下面的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>

5 个答案:

答案 0 :(得分:2)

你错过了一步。您将textnode添加到span而不是链接。然后你应该把链接放到跨度......

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

答案 1 :(得分:1)

$("<a/>").attr({href:"http://google.com"}).html("google").appendTo("#span");

这里是小提琴http://jsfiddle.net/wYdZb/1/

答案 2 :(得分: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);

答案 3 :(得分: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元素以显示所有元素。
  3. 例如:http://jsfiddle.net/bz6bu/

答案 4 :(得分:0)

使用jquery的append

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