点击html页面中的添加按钮时,应在html页面上显示div,多次点击时应显示多个div。每个div都应该有X图标,在点击x时,div应该从UI中消失。此外,它应该维护动态生成的div元素的id数组,这些id应该在控制台上显示,并且只要删除了特定的div,就应该删除id。
这段代码工作正常,但是我可以使用数组,每次创建div时都会生成动态id,删除div时应删除id。?
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Click the button to make a Division element.</p>
<button id="button" onclick="myFunctionAdd()">Add</button>
<div id="myDIV">
</div>
<script>
var counter=1;
function myFunctionAdd()
{
var x = document.createElement("DIV");
x.id="div"
var divNumber = counter;
counter++;
console.log("Div Number: "+ divNumber + " is created");
var z= document.createElement("button");
z.id="btn";
x.setAttribute("style", "border :1px solid;height: 250px; width: 250px; top: 741px; left: 491px; padding:10px; margin: 50px;");
z.setAttribute("style", "background: #000 url(/home/subodh/Desktop/Widget/icon_incorrect.svg) no-repeat 0px 0px; height: 30px; width:40px; top: 6px; left: 4px; float: right; margin: 0px; padding:0px; clear: both; float:right;");
x.appendChild(z);
document.body.appendChild(x).appendChild(z);
z.onclick = function remove(btn)
{
console.log("Div Number: "+ divNumber + " is deleted");
x.parentElement.removeChild(x);
}
}
</script>
</body>
</html>
答案 0 :(得分:2)
请参阅此示例:https://codepen.io/dsomekh/pen/GEVNWb
function Clone() {
var clone = document.getElementById('thediv').cloneNode(true); // "deep" clone
document.getElementById("container").appendChild(clone);
}
function Delete(button) {
var parent = button.parentNode;
var grand_father = parent.parentNode;
grand_father.removeChild(parent);
}
.mydiv {
border: 2px solid red;
}
<div class="container" id="container">
<div class="mydiv" id="thediv">
I am the div
<button type="button" onclick="Clone()" ) ">Clone</button>
<button type="button " onclick="Delete(this) ")">Delete</button>
</div>
<div>
答案 1 :(得分:0)
尝试这个
function adddiv() {
document.body.innerHTML += '<div id=' + Math.random() + '><button id="btn" onclick=closediv(this)>X</button>' + Math.random() + '</div>';
}
function closediv(e) {
var par = $(event.target).parent();
par.remove();
}
&#13;
div {
border: solid 1px red;
width: 150px;
height: 100px;
margin: 2px;
}
#btn {
clear: both;
float: right;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add" onclick=adddiv()>Add</button>
&#13;
现在所有div都使用唯一ID创建并使用javascript