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

How to link text from a function to the same webpage using document.getElementbyID('').innerHTML?

本文关键字:文本 链接 函数 document 何使用 getElementbyID innerHTML      更新时间:2023-09-26

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

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

您的代码有一些问题。

  • 您将innerHTML设置为空字符串,而不是下一行的字符串
  • 您将document.getElementById错误地键入为document.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()

此外,

丢失了很多东西。byID此处为byID。'd'应该很小,而且没有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>

因此,如果我理解正确,当您单击单击此处部分时,您希望该文本显示在页面的"defArea"部分。

你很亲密。你只需要在页面上添加一个链接就可以实现这一点。

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

http://jsfiddle.net/NUqdZ/

编辑根据评论:

其他错误,我纠正了没有提及。。。

  • innerHTML语法不正确。应为:innerHTML="INSERT TEXT HERE",两者之间不带分号。这将结束该语句,而不会将文本插入到div中
  • 更新了jsfiddle以反映以下建议的更改
  • 其文档.getElementById未获取ElementByID