点击后将文本添加到一个div中

3

我刚开始学习JavaScript,但我觉得我已经懂了。我不明白为什么它不能工作。当按钮被点击时,我需要将“this text”作为二级标题的格式插入到theDiv中。我尝试过各种方法,甚至使用函数。这个例子看起来应该可以工作,但是却没有。我必须只使用JavaScript来使其工作,不能用jQuery - 因为我还不会。

<html>
  <h1 id="header">Header in progress</h1>
  <body>
    <p>
      <input type="button" id="theButton" value="click me!" onclick="document.getElementById('theDiv').innerHTML('This is new.')">
    </p>
    <h3><div id="theDiv"></div></h3>
  </body>
</html>
3个回答

3
document.getElementById("theDiv").textContent = 'This is dynamically added text';

1
@Uni:不用客气,请确认答案是否解决了你的问题。 - Gurpreet Singh

2

使用document.getElementById('theDiv').innerHTML = 'This is new.'

你需要在引号中传递div的id,而innerHTML是属性而不是函数

演示


哇,这个点赞速度真快...除此之外,我同意,问题在于你没有用''包裹你的div名称。 - PatchGuru
谢谢,我已经改了,但仍然没有任何作用(请参见更新的代码)。 - Uni

0

第一步:获取您的按钮和HTML元素。 第二步:将单击侦听器添加到按钮上。 第三步:将文本添加到您的HTML元素中。

const btn = document.getElementById('theButton');
const myText = document.getElementById('theDiv');

btn.addEventListener('click', function(){
  const myInsertText = 'Hello World !';
myText.innerHTML = myInsertText;

});
 <button id='theButton'>bouton</button>
 <p id="theDiv"></p>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接