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
Onclick add text to a div
提问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 theDiv
when 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
回答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>