在<a>-tags with Javascript</a>中添加文字

时间:2009-07-20 09:32:29

标签: javascript append

我现在可以通过以下方式将文字插入<div>标记:

<script type="text/javascript">
  function doSomething(){
    var lbl = document.getElementById('messageLabel');
    lbl.innerHTML = "I just did something.";    
  }  
</script>

</head>
<body>
  <div>
  <div id="messageLabel"></div>
  <input type="button" value="Click Me!" onclick="doSomething();" />

  </div>

我的问题:如何将文字附加到链接?

不起作用的示例12

3 个答案:

答案 0 :(得分:3)

var anchor = document.getElementById('anchorID');
anchor.innerHTML = anchor.innerHTML + " I just did something.";  

应该添加“我刚刚做了些什么。”到你当前的锚文本

答案 1 :(得分:3)

从上面发布的示例中,请尝试使用以下代码。我将div标签的id更改为与您尝试更改的链接不同,并更改了代码以修改锚点的href。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Javascript Debugging with Firebug</title>
<script type="text/javascript">
  function addLink(){
    var anchor = document.getElementById('link');
    anchor.href += "Dsi7x-A89Mw";
  }  
</script>

</head>
<body>
  <div>
  <div id="linkdiv"></div>
  <input type="button" value="Click Me!" onclick="addLink();" />

  <a id="link" href="http://www.youtube.com/watch?v=">Click here</a>
  </div>
</body>
</html>

答案 2 :(得分:2)

innerText或textContent可用于访问标签的文本:

var anchor = document.getElementById('something');
anchor.innerText += "some text";    

var anchor = document.getElementById('something');
anchor.textContent += "some text";

但是,这些不是跨浏览器的,所以你最好使用innerHTML:

var anchor = document.getElementById('something');
anchor.innerHTML += "some text";  

见:

http://www.quirksmode.org/dom/w3c_html.html