javascript Onclick 将文本添加到 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19609022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:09:29  来源:igfitidea点击:

Onclick add text to a div

javascripthtmlbuttononclick

提问by Uni

I just started learning Javascript, but I really thought I knew this. I can't figure out why it won't work. I need it to insert "this text" formatted as a level 2 header into theDivwhen the button is clicked. I've tried every way, even with a function. This example seems like the way it should work, but doesn't. I have to make this work with Javascript only, no JQuery - I don't know any yet.

我刚开始学习 Javascript,但我真的以为我知道这一点。我无法弄清楚为什么它不起作用。我需要它在theDiv单击按钮时插入格式为 2 级标题的“此文本” 。我已经尝试了各种方法,即使是一个函数。这个例子似乎是它应该工作的方式,但事实并非如此。我必须只使用 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>

回答by Gurpreet Singh

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

回答by Satpal

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

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

You need to pass idof div with in ''(quotes)and innerHTMLis property not a function

您需要id使用 in传递div''(quotes)并且innerHTML是属性不是函数

Demo

演示

回答by Nyz Zakaria Nya

first step: get your button, and your html elements. 2nd step : add click listener to the button 3th step: add text into your html element.

第一步:获取您的按钮和您的 html 元素。第 2 步:将单击侦听器添加到按钮第 3 步:将文本添加到您的 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>