我有一個動態表單,您可以隨時添加文本字段。 它的工作原理,但問題是我已經實現的刪除按鈕清除整個表單,而我希望它清除最後創建的項目。(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