Javascript:DIV AppendChild

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10328210/
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-08-24 00:53:17  来源:igfitidea点击:

Javascript:DIV AppendChild

javascriptappendchild

提问by user1357872

In the below code "objTo"is a div to which i need to insert multiple number of div. when i use the code for the first time its working.but on the next time its overwriting the existing code.

在下面的代码中"objTo"是一个 div,我需要向其中插入多个 div。当我第一次使用代码时,它可以工作。但下次它会覆盖现有的代码。

     <script>

var divtest= document.createElement("div");        
divtest.innerHTML = "<div>new div</div>"         
objTo.appendChild(divtest)
    </script>

Where am i going wrong?

我哪里出错了?

回答by Marc Uberstein

I have made a very simple working version for you :

我为您制作了一个非常简单的工作版本:

http://jsfiddle.net/hQKy9/

http://jsfiddle.net/hQKy9/

Multiple clicks works the whole time :

多次点击始终有效:

Script

脚本

function addDiv() {
    var objTo = document.getElementById('container');
    var divtest = document.createElement("div");
    divtest.innerHTML = "new div";
    objTo.appendChild(divtest);
}

Html

html

<div id="container"></div>

<input type="button" onclick="addDiv();" value="Click here to add div"/>