问题描述
我正在使用javascript生成动态字段集.为了添加字段,我使用以下函数(此函数实际上添加了多个字段)
I am generating a dynamic fieldset with javascript. For adding fields, I use the following function (this function actually adds more than one field)
//添加测试
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+"'/> <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'/> <a href='javascript:addObject();'>+ add question</a><br/><br/><hr/><br/></div>";
}
我使用innerHTML
而不是append
,因为我不得不附加很多代码,这种方式的标记要短得多.
I use innerHTML
instead of append
because there is a lot of code i'd have to append, the markup is so much shorter this way.
现在,我的问题是,每当我添加(或删除)一个字段时,其他动态生成的数据中的所有数据都会丢失.我怎样才能解决这个问题?保存该值,然后将其添加到每个字段中,对于我而言,这将再次变得非常复杂.有什么想法吗?
Now, my problem is that whenever I add (or remove) a field, all the data from the other dynamically generated data would be lost. How can I fix this? Saving the value and then adding it to every field would be again, very complicated in my case. Any ideas?
推荐答案
设置父元素的innerHTML会导致整个内容被序列化然后重新解析,从而丢失了进程中的所有值(不是重新序列化为值属性).我可以想到三种解决方法:
Setting the innerHTML of the parent element causes the entire content to be serialized and then re-parsed, losing all the values in the process (the values aren't serialized back into value attributes). I can think of three workarounds:
- 使用createElement创建外部div(testContainer),设置其innerHTML,然后将div附加到父元素中
- 使用DOM创建所有元素.创建一堆辅助函数以简化元素的创建很简单.
- 使用jQuery为您完成所有这一切:
$(location).append('html goes here');
这篇关于添加新字段时,动态生成的表单字段会失去价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!