gpt4 book ai didi

javascript - (JS) 如何删除动态创建的最后一个元素?

转载 作者:行者123 更新时间:2023-11-28 13:27:28 24 4
gpt4 key购买 nike

我有一个动态表单,您可以在其中动态添加文本字段。它有效,但问题是我实现的删除按钮会清除整个表单,而我希望它只是清除创建的最后一个项目。

这是我的代码:

<!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);
}

FIDDLE

关于javascript - (JS) 如何删除动态创建的最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27929124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com