Sat*_*uga 0 html javascript css jquery
我试图使用下面的代码动态生成div,但新的div不包含我现有的div容器的元素.
Below is the code which I tried:
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/sathish_panduga/bvb7msne/2/
我们如何动态地创建我的内部div的所有元素(都来自inner1和inner2 div)到新生成的元素中,而不为现有div中的每个元素编写追加函数,我在那里缺少什么?
另外,如何删除使用按钮点击新创建的div?
$(function() {
$("#add").click(function() {
div = document.createElement('div');
$(div).addClass("inner").html("new inner div");
$("#container").append(div);
});
});Run Code Online (Sandbox Code Playgroud)
#container {
border: 1px solid red;
width: 100%;
height: 330px;
}
.inner {
border: 1px solid green;
width: 100%;
height: 300px;
}
.inner1 {
position: relative;
width: 50%;
height: 100%;
float: left;
background: #808080;
background-color: #808080;
overflow: hidden;
}
.inner2 {
position: relative;
width: 50%;
height: 100%;
float: left;
background: green;
background-color: green;
overflow: hidden;
}Run Code Online (Sandbox Code Playgroud)
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.0.min.js"></script>
<div id="container">
<div class="inner">
<div class="inner1">
<section>
Enter Name:<input type="text" /><br /><br />
<img src="https://upload.wikimedia.org/wikipedia/commons/5/54/Colorful_Parrots_Couple.jpg" width="200" height="200" />
</section>
</div>
<div class="inner2">
<section>
Enter Name:<input type="text" /><br /><br />
<img src="https://upload.wikimedia.org/wikipedia/commons/5/54/Colorful_Parrots_Couple.jpg" width="200" height="200" />
</section>
</div>
</div>
</div>
<button id="add">Add DIV</button>Run Code Online (Sandbox Code Playgroud)
你可以使用.clone(),
$("#add").click(function () {
$("#container").append($(".inner").clone());
});
$("#remove").click(function () {
$("#container .inner:last").remove();
});
Run Code Online (Sandbox Code Playgroud)
clone() 将返回指定元素的副本append() 将添加一个元素作为指定父元素的最后一个子元素.remove() 将从dom中删除指定的元素