2015-01-13 19 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); 
    } 
} 
相關問題