【发布时间】:2021-05-11 05:49:26
【问题描述】:
我的网页上有一个执行“AddBox()”函数的按钮。此函数创建一个名为“box”的 div,并在该 div 中创建其他元素,如(另一个)div、标签、输入和按钮。 每次创建“盒子”时,都会获得一个唯一的 id,即“box1”、“box2”、“box3”、...
现在我需要一种方法来删除某个框。在每个盒子中,我还创建了一个按钮,作为移除盒子的一种方式。该按钮称为“buttonRemove”。删除框的函数称为“removeBox()”。
我试图在创建按钮时将“removeBox()”作为 onclink 属性。然而,这个函数在创建时也会被执行。
如何将“removeBox()”函数赋予“removeBox”按钮,以便我可以添加多个“框”并删除单击“删除”按钮的框。
var count = 0;
function addBox() {
count++
var box = document.createElement("div");
box.id = "box" + count;
var stepTitle = document.createElement("h2")
stepTitle.innerText = "Title " + count;
var divName = document.createElement("div");
divName.className = "fields";
var labelName = document.createElement("label");
labelName.htmlfor = "Name";
labelName.innerHTML = "Name";
var inputName = document.createElement("input");
inputName.type = "text";
inputName.name = "Name";
inputName.id = "Name";
var buttonRemove = document.createElement("button");
buttonRemove.innerText = "Remove box" + count +" with Title "+count;
buttonRemove.type = "button";
divName.appendChild(labelName);
divName.appendChild(inputName);
box.appendChild(stepTitle);
box.appendChild(divName);
box.appendChild(buttonRemove)
document.getElementById("container").appendChild(box);
}
function removeBox(){
document.getElementById().remove();
}
.fields {
display: flex;
flex-direction: row;
}
label {
flex-basis: 10rem;
}
input{
width: 50%;
}
<body>
<button type="button" onclick="addBox()">Add box</button>
<div id="container"></div>
</body>
【问题讨论】:
-
这样做:
function removeBox(num) { document.getElementById('box'+num).remove() }
标签: javascript html jquery