我有兩個文本框和兩個名爲add和remove的按鈕。要求是在當前框中添加更多框。我以某種方式設法添加框,但刪除框的要求不起作用。請幫助解釋爲什麼此代碼無法正常工作,並且如果可能的話,請提供可行的解決方案使用javascript添加和刪除框
function addFunction(){
var element = document.createElement("input");
var parent = document.getElementById("form1");
parent.appendChild(element);
}
function removeFunction(){
var child = document.getElementsByTagName("input");
var parent = document.getElementById("form1");
for (var i = 0; i > child.length; i++) {
parent.removeChild(child[i]);
};
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form1" style="margin-left: 40%; margin-top: 100px;">
<input type="text" id="one"><br><br><br>
<input type="text" id="two"><br>
<p id ="demo"> </p>
</form>
<button style="margin-left: 40%;" type="button" value="ADD" id="addButton" onclick="addFunction()">ADD</button>
<button style="margin-left:50px;" type="button" value="REMOVE" id="removeButton" onclick="removeFunction()">REMOVE</button>
</body>
</html>
你需要克隆'node',然後再追加同樣的https://developer.mozilla.org/en/docs/Web/API/Node/cloneNode – gurvinder372