简体   繁体   English

如何在JavaScript中动态添加和更改div?

[英]How can I dynamically add and change divs in javascript?

I have the following code: 我有以下代码:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

function timeMsg()
{
var t=setTimeout("enterquestion()",900000);
}


function enterquestion()
{
document.getElementById("questions").innerHTML += '<p>'  + document.getElementById("question").value;


}
</script>
</head>
<body>

<h1>Testing Website</h1>
<p id="questions"></p>

<input type="text" name="question" id="question" />
<button type="button" onclick="timeMsg()">Enter question</button>


</body>
</html> 

All this code does is it allows the user to enter a question and then it adds the question to the list of questions after 15 minutes have passed. 此代码的全部作用是允许用户输入问题,然后在15分钟后将问题添加到问题列表中。

All I'd like to do to the code is make it so that it immediately puts the text "QUESTION RECORDED" in the place where the question will show up, then instead of simply adding the question to the end, it should replace the "QUESTION RECORDED" text with the question. 我要对代码进行的所有操作就是将其制成,以便立即将文本“ QUESTION RECORDED”放在要显示问题的位置,然后代替简单地将问题添加到末尾,而不是简单地将问题添加到末尾问题记录”文本和问题。

I can't figure out how to do it in such a way that you can enter multiple questions at the same time. 我无法弄清楚如何同时输入多个问题。

Any help is appreciated, 感谢您的帮助,

Thanks! 谢谢!

The innerHTML property is handy when you want to replace the entire content of an element but not for adding or inserting child nodes. 当您要替换元素的全部内容而不是添加或插入子节点时,innerHTML属性非常方便。 For that, it's easier to use createElement . 为此,使用createElement更容易。

The following is an example to get you going: 以下是使您前进的示例:

<script>
function addDiv(parent, text) {
  var div = document.createElement('div');
  div.appendChild(document.createTextNode(text));
  parent.appendChild(div);
}
</script>

<form action="serverprocess" onsubmit="return false;">
  <input type="text" name="qText" value="Question text">
  <button onclick="
    addDiv(document.getElementById('container'), this.form.qText.value);
  ">Add question</button>
</form>
<div id="container"></div>

In the above, if javascript isn't available or active, the form will be submitted and processing can be done on the server. 在上述方法中,如果无法使用javascript或未启用javascript,则会提交表单,并且可以在服务器上进行处理。 If it's available, then it will be processed locally and the form won't submit, though submission should really be based on successful completion of the actions. 如果可用,它将在本地处理,并且不会提交表单,尽管提交实际上应该基于成功完成操作。

I'll leave that for you to ponder. 我留给你去思考。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM