2017-04-20 64 views
0

我有兩個文本框和兩個名爲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>

+0

你需要克隆'node',然後再追加同樣的https://developer.mozilla.org/en/docs/Web/API/Node/cloneNode – gurvinder372

回答

0
for (var i = 0; i < child.length; i++) { 
     parent.removeChild(child[i]); 
    }; 

你已經在你的循環得到了錯誤的條件。你的i在開始時總是0,並且小於包含節點元素的數組的長度,所以循環無法啓動。 P.s.你不需要var i

+0

我真是太笨了..感謝你的解釋和幫助... – Daredevil

0

你的for循環是錯誤之前:

 for (var i = 0; i > child.length; i++) { 
      parent.removeChild(child[i]); 
     }; 

您需要更改「>」爲「<」

+0

是的..現在它的工作..我是如此愚蠢..感謝您的幫助... – Daredevil

0

更換你>條件的for循環與<。您希望執行for循環,直到達到child.length。

+0

是的..現在它的工作..我是如此愚蠢..感謝您的幫助... – Daredevil

+0

Vote如果這對您有用,請將其標記爲已接受的答案。 – Felix

+0

是的,我做到了,但它的說法是,我的最高票數已錄製,但由於我的名聲不到15位,所以不會公開顯示。 – Daredevil