我正在使用jQuery函数来克隆包含一组输入元素的DIV:
<div class="history-form-fields"> <div class="row"> <label for="History_0_type">Type</label> <select name="History[0][type]" id="History_0_type"> <option value="">Select</option> </select> </div> <div class="row"> <label for="History_0_name">Name</label> <input type="text" name="History[0][name]" id="History_0_name" /> </div> <div class="row"> <label for="History_0_year">Year</label> <select name="History[0][year]" id="History_0_year"> <option value="">Select</option> </select> </div> </div> <input id="addAnother" type="button" value="Add Another" />
当克隆此DIV时,需要修改输入元素NAME和ID标记,以便我们可以识别服务器端脚本中的数据.
var counter = 0; $('#addAnother').click(function(){ var divCloned = $('.history-form-fields:first').clone(); divCloned.insertAfter('.history-form-fields:last'); initNewInputs(divCloned.children('.row'),++counter); }); function initNewInputs(divs,idNumber) { var inputs = divs.children('input,select').get(); // find all the INPUT and SELECT tags for(var i in inputs) { inputs[i].id = inputs[i].id.replace(/\d+/,idNumber); inputs[i].name = inputs[i].name.replace(/\d+/,idNumber); } }