我有一个动态表单,您可以在其中动态添加文本字段。 它有效,但问题是我实现的删除按钮会清除整个表单,而我希望它只是清除创建的最后一个项目。
这是我的代码:
<!DOCTYPE html>
<html>
<body>
<div id="Form1"></div>
<button type="button" onClick="createNode1()">+</button>
<button type="button" onClick="deleteNode1()">-</button>
<script>
function createNode1(){
var input = document.createElement("input");
input.type = "text";
input.placeholder = "Enter Text Here";
document.getElementById("Form1").appendChild(input); // put it into the DOM
}
//CLEARS THE FORM IF YOU MADE A MISTAKE
function deleteNode1(){
var node = document.getElementById('Form1');
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
}
</script>
</body>
</html>
最佳答案
只需删除 while 循环,它就会迭代并删除所有剩余的子节点
function deleteNode1(){
var node = document.getElementById('Form1');
if (node.hasChildNodes())
node.removeChild(node.lastChild);
}
关于javascript - (JS) 如何删除动态创建的最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929124/