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

时间:2015-01-13 18:36:40

标签: javascript html

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

这是我的代码:

<!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>

2 个答案:

答案 0 :(得分:3)

只需删除while循环,只要有剩余的就迭代并删除所有的childNodes

function deleteNode1(){
    var node = document.getElementById('Form1');
    if (node.hasChildNodes())
         node.removeChild(node.lastChild);
}

FIDDLE

答案 1 :(得分:2)

正如adeneo所说,或者如果Form1为空则避免JS错误,请将while替换为if

function deleteNode1(){
    var node = document.getElementById('Form1');
    if(node.hasChildNodes()) {
        node.removeChild(node.lastChild);
    }
}