簡體   English   中英

如何使用 JavaScript 添加指向一段文本的鏈接?

[英]How do I add a link to a span of text using 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://example.com/index.aspx?objectid=" + oTodayImage.pid);
var span = document.createElement("span");
var txt = link.href;
var textNode = document.createTextNode(txt);
span.appendChild(textNode);
</script>

你少了一步。 您將 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);
$("<a/>").attr({href:"http://google.com"}).html("google").appendTo("#span");

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

您還可以設置鏈接的innerHTML ,而不是創建文本節點。 最后,在創建此span您需要將其附加到某個容器中,現在我已將其附加到body

工作演示

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

使用 jquery 的append

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM