如何使用document.getElementbyID('')。innerHTML将函数中的文本链接到同一网页?

时间:2014-04-17 17:04:56

标签: javascript html function hyperlink innerhtml

尝试将此信息链接到"点击此处查看.."并让它显示在同一页面上

<script type="text/javascript">
  function rhinoinfo(){
    document.getElementByID('defArea').innerHTML="";
    "There are five different species of rhinoceros. The name rhinoceros means  
    ‘nose horn’ and is often shortened to rhino. It comes from the Greek words  
    rhino (nose) and ceros (horn).White rhinoceros are the second largest land  
    mammal. Rhinos can grow to over 6 feet tall and more than 11 feet in length.  
    Rhinoceros have thick, sensitive skin. Source: Savetherhino.org";
  }
</script>


<p>Click here to see information about the rhino.</p>
</div>
<div id="defArea">
  <p></p>
</div>
</body>
</html>

3 个答案:

答案 0 :(得分:0)

您的代码存在一些问题。

  • 您将innerHTML设置为空字符串,而不是下一行的字符串
  • 您输错document.getElementByIddocument.getElementByID
  • 当用户点击p标记
  • 时,您没有设置处理程序来调用代码

这是一个有用的版本http://jsfiddle.net/mendesjuan/Ljf28/1/

// I added an ID to the p, so you can hookup the handler from JS
document.getElementById('clickme').addEventListener('click', function(){
    document.getElementById('defArea').innerHTML = "There are five different species of rhinoceros. The name rhinoceros means      ‘nose horn’ and is often shortened to rhino. It comes from the Greek words rhino (nose) and ceros (horn).White rhinoceros are the second largest land mammal. Rhinos can grow to over 6 feet tall and more than 11 feet in length. Rhinoceros have thick, sensitive skin. Source: Savetherhino.org";    
});

您将innerHTML设置为空字符串,而不是下一行的字符串。当然,当用户点击p。

时,您还必须致电rhinoinfo()

另外,

答案 1 :(得分:0)

因此,如果我理解正确,当您单击“单击此处”部分时,您希望该文本显示在&#34; defArea&#34;页面的一部分。

你非常接近。您只需要添加一个指向页面的链接即可实现。

<a href="#" onclick="functionName()">Click here</a>...

http://jsfiddle.net/NUqdZ/

修改根据评论:

我在没有提及的情况下纠正的其他错误......

  • innerHTML语法不正确。应该是:innerHTML="INSERT TEXT HERE"两者之间没有分号。这将结束声明,而不是将文本插入div。
  • 更新了jsfiddle以反映下面建议的更改
  • 其document.getElementById不是getElementByID

答案 2 :(得分:0)

Coupe of things is missing。 byID hereId。 &#39; d&#39;应该很小,没有onclick事件。以下是代码

<html>
<script type="text/javascript">
function rhinoinfo(){
    document.getElementById('defArea').innerHTML = 
        "<P>There are five different species of rhinoceros. The name rhinoceros means  " +
        "'nose horn' and is often shortened to rhino. It comes from the Greek words " +
    "rhino (nose) and ceros (horn).White rhinoceros are the second largest land  " +
    "mammal. Rhinos can grow to over 6 feet tall and more than 11 feet in length.  " +
    "Rhinoceros have thick, sensitive skin. Source: Savetherhino.org</P>";
 }
</script>

<body>
<p onclick="javascript:rhinoinfo();">Click here to see information about the rhino.</p>
</div>
<div id="defArea">
</div>
</body>
</html>