2010-05-13 31 views
2

我正在使用javascript生成動態字段集。對於添加字段,我用下面的功能(該功能實際上增加了多個字段)當添加新字段時,動態生成的表單域會丟失值

//添加測試

function addTest() { 
    var location = document.getElementById('addTestLocation'); 
    var num = document.getElementById('addTestCount'); 
    var newnum = (document.getElementById('addTestCount').value -1)+ 2; 
    num.value = newnum; 
    location.innerHTML += "<div id='testContainer_"+newnum+"'><label for='test_"+newnum+"'>Test name: </label><input type='text' name='test_"+newnum+"' id='test_"+newnum+"'/>&nbsp;&nbsp;&nbsp;<a href='javascript: removeTest("+newnum+")'>- Remove test</a><br/><br/><span id='addObjectLocation'></span><br/><select id='select_"+newnum+"'><option>True or False</option><option>Single choice</option><option>Multiple choice</option><option>Short definition</option><option>Fill in the blanks</option></select><input type='hidden' id='addObjectCount' value='0'/>&nbsp;&nbsp;&nbsp;<a href='javascript:addObject();'>+ add question</a><br/><br/><hr/><br/></div>"; 
} 

我用innerHTML代替append因爲有大量的代碼我不得不追加,這種方式的標記非常短。

現在,我的問題是,每當我添加(或刪除)一個字段,其他動態生成的數據中的所有數據都將丟失。我怎樣才能解決這個問題?保存該值然後將其添加到每個字段將再次,在我的情況下非常複雜。有任何想法嗎?

+0

(.. -1)+2? :) – Alec 2010-05-13 12:51:46

回答

2

設置父元素的innerHTML會導致整個內容序列化,然後重新解析,從而失去進程中的所有值(值不會序列化回值屬性)。我能想到的三種解決方法:

  1. 創建使用的createElement您的外層div(在testContainer),設置它的innerHTML,然後在div追加到父元素
  2. 創建使用DOM的所有元素。創建一大堆輔助函數來簡化創建元素是很簡單的。
  3. 使用jQuery它做的一切都是爲了你:$(location).append('html goes here');
+0

我想過使用jquery,但後來,我想我會更像這樣學習:D 解決方案#1像魅力一樣工作,豎起大拇指! – 2010-05-13 13:04:26

相關問題