2015-01-13 81 views
0

我有一个动态表单,您可以随时添加文本字段。 它的工作原理,但问题是我已经实现的删除按钮清除整个表单,而我希望它清除最后创建的项目。(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> 
+0

“我已经实现的删除按钮” - >'while(node.hasChildNodes())'有趣...... – Jonathan

+0

为什么你要循环使用deletenode代码? – j08691

回答

3

只需卸下while循环,它迭代,并且只要有任何左

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

FIDDLE

+0

注意,如果在#Form1为空时点击[ - ],则会显示“无法执行”removeChild'“ – KyleK

2

由于adeneo说或删除所有的childNodes如果Form1为空,请避免出现JS错误,请用if替换while

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