[英]How can I display a new div with text after a user inputs this text and hits submit?
I'm trying to simulate a chat messaging system using pure JS (no server though, so really just uploading and displaying text) but am having trouble as I'm pretty new to JavaScript.我正在尝试使用纯 JS 模拟聊天消息系统(虽然没有服务器,所以实际上只是上传和显示文本),但由于我对 JavaScript 还很陌生,因此遇到了问题。 I wrote this code but nothing happens when I click submit.
我写了这段代码,但当我点击提交时没有任何反应。 Is my code having a huge error anywhere that I am not catching?
我的代码在我没有捕捉到的任何地方都有一个巨大的错误吗? If so, how can I fix it?
如果是这样,我该如何解决?
I am trying to use the javascript function to generate a div under the class container, with parent div chatMsg.我正在尝试使用javascript函数在类容器下生成一个div,父div chatMsg。
<div id="chatMsg" class = "chatMsg" >
<div class="container">
//some other HTML here
</div>
</div>
<div class = "sendText">
<form name = "sendMsg">
<textarea name="Message" class="msg" ></textarea>
<input type="submit" name = "submit" value="Send!" onclick = "addChatMessage()">
</form>
</div>
<script>
function addChatMessage() {
var chat = document.getElementById('Message'); // finds the container
var div = document.createElement('div');
div.id = "newMsg";
div.className = "container";
div.innerHTML = chat.value;
var parDiv = document.getElementById('chatMsg');
parDiv.appendChild(div);
}
</script>
A few things...一些东西...
1) You need to give the textarea an id
attribute: 1) 你需要给 textarea 一个
id
属性:
<textarea id="Message" name="Message" class="msg" ></textarea>
Now, you can use document.getElementById('Message')
to get it.现在,您可以使用
document.getElementById('Message')
来获取它。
2) You should create new elements with unique ids. 2) 您应该创建具有唯一 ID 的新元素。 A counter variable could be used to increase the id by one each time:
计数器变量可用于每次将 id 增加 1:
var counter = 0;
div.id = "newMsg" + counter++;
div.className = "container";
div.innerHTML = chat.value;
3) Use an input type of button
instead of submit
if you don't want it to post to a server. 3) 如果您不想将其发布到服务器,请使用输入类型的
button
而不是submit
。
<input type="button" id="submit" value="Send!" onclick = "addChatMessage()">
Putting it all together:把它们放在一起:
var counter = 0; function addChatMessage() { var chat = document.getElementById('Message'); // finds the container var div = document.createElement('div'); div.id = "newMsg" + counter++; div.className = "container"; div.innerHTML = chat.value; var submitMsg = document.getElementById('submit'); var parDiv = document.getElementById('chatMsg'); parDiv.appendChild(div); }
<div id="chatMsg" class = "chatMsg" > <div class="container"> //some other HTML here </div> </div> <div class = "sendText"> <form name = "sendMsg"> <textarea id="Message" name="Message" class="msg" ></textarea> <input type="button" id="submit" value="Send!" onclick = "addChatMessage()"> </form> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.