2013-01-14 166 views
2

我創建了一段Javascript代碼,您可以在其中創建多個問題並提供多個答案。問題的數量最多爲20。當我點擊「添加問題」時,它會添加一個帶有兩個答案的問題。當我填寫一些輸入字段並單擊「添加問題」時,它會清空我的所有文本字段。這怎麼可能?Javascript,添加輸入字段清空所有其他輸入字段

var fields = 0; 
var qAmount = 0; 
var array = new Array(); 

function addInput() { 
    if (fields != 2) { 
    qAmount++; 
    var element = document.getElementById('texty'); 
    element.innerHTML += "" + 
     "<label>Question " + qAmount + "</label><span class='field'><input type='text' class='longinput' name='question" + qAmount + "' /></span>" + 
     "<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-1' /> <input type='text' name='answer" + qAmount + "-1'> Answer 1</input></span>" + 
     "<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-2' /> <input type='text' name='answer" + qAmount + "-2'> Answer 2</input></span>" + 
     "<div id='a" + qAmount + "'></div><br/>" + 
     "<span class='field'><a style='cursor: pointer' onclick='addAnswer(" + qAmount + ")'>Add answer</a></span><br /><br />"; 
     fields += 1; 
     array[qAmount] = 2; 
    } 
} 

回答

3

的問題是,當你做element.innerHTML + = ...你做什麼樣的頁面上已經存在的淺複製和重新插入它作爲一個覆蓋。所以你不保留已經輸入的值。你應該做的是將新的DOM元素附加到元素。

下面是如何創建的HTML字符串元素的鏈接:Creating a new DOM element from an HTML string using built-in DOM methods or prototype

而如何追加那些元素:https://developer.mozilla.org/en-US/docs/DOM/Node.appendChild

像這樣的東西應該做的伎倆:(可能需要一些調試)

var fields = 0; 
var qAmount = 0; 
var array = new Array(); 
var element = document.getElementById('texty'); 

function addInput() { 
    var div, s; 
    if (fields != 2) { 
    qAmount++; 
    s = "<label>Question " + qAmount + "</label><span class='field'><input type='text' class='longinput' name='question" + qAmount + "' /></span>" + 
     "<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-1' /> <input type='text' name='answer" + qAmount + "-1'> Answer 1</input></span>" + 
     "<span class='field'><input type='radio' name='question" + qAmount + "-correctanswer' value='answer" + qAmount + "-2' /> <input type='text' name='answer" + qAmount + "-2'> Answer 2</input></span>" + 
     "<div id='a" + qAmount + "'></div><br/>" + 
     "<span class='field'><a style='cursor: pointer' onclick='addAnswer(" + qAmount + ")'>Add answer</a></span><br /><br />"; 
     div = document.createElement('div'); 
     div.innerHTML = s; 
     element.appendChild(div); 
     fields += 1; 
     array[qAmount] = 2; 
    } 
} 
+0

哦,我明白了!謝謝!我會仔細看看的。 –

+0

我正在試圖找出如何去做,但你說「將新的dom元素添加到元素」。我有點新的Javascript(這是我認爲的,我寫的第二段代碼)..你可以向正確的方向推一下嗎? –

+0

工作就像它應該!非常感謝!我明白了這是如何運作的。 –

相關問題