我正在尝试使用下面的 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>
最佳答案
你错过了一步。您将文本节点而不是链接添加到了范围中。那么你应该将链接放入跨度中...
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);
关于javascript - 如何使用 JavaScript 添加指向一段文本的链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7135334/