我有一个动态表单,您可以随时添加文本字段。 它的工作原理,但问题是我已经实现的删除按钮清除整个表单,而我希望它清除最后创建的项目。(JS)如何删除动态创建的最后一个元素?
这里是我的代码:
<!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(node.hasChildNodes())'有趣...... – Jonathan
为什么你要循环使用deletenode代码? – j08691