克隆forms和增量

我有一个下面的表格,我想克隆,增加id(att1)和它的输入,textareas等,并附加到与会者div。 任何帮助非常感谢。 一直在破坏我的头脑……

我只有……

$(function () { var index = 1; $(".add").click(function () { index++; $("#att1").clone(true).removeAttr("id").attr("id", "att" + index).appendTo("#attendees"); alert(index); }); }); 

HTML:

  
Attendee 1 Booking Details

Please include any infomation relating to dietary/ access/special requirements you might have.

Add more

看小提琴 。

将一个class级attendee添加到div id="att1"

  

和JS:

 $(function(){ var template = $('#attendees .attendee:first').clone(), attendeesCount = 1; var addAttendee = function(){ attendeesCount++; var attendee = template.clone().find(':input').each(function(){ var newId = this.id.substring(0, this.id.length-1) + attendeesCount; $(this).prev().attr('for', newId); // update label for (assume prev sib is label) this.name = this.id = newId; // update id and name (assume the same) }).end() // back to .attendee .attr('id', 'att' + attendeesCount) // update attendee id .prependTo('#attendees'); // add to container }; $('.add').click(addAttendee); // attach event }); 

试试这个

  empty_html = $('#att1').html(); $('.add').click(function() { last_id = $('#attendees div:last').attr('id').replace('attr',''); next_id = last_id++; new_div = $('
' + empty_html +'
'); $('#attendees').append(new_div); });

需要对HTML进行一些调整,我会将添加链接移出与会者div。

这个例子可能对你有帮助。 例

 $(function() { var scntDiv = $('#p_scents'); var i = $('#p_scents p').size() + 1; $(document).on('click','#addScnt', function() { $('

Remove

').appendTo(scntDiv); i++; return false; }); $(document).on('click','#remScnt', function() { if( i > 2 ) { $(this).parents('p').remove(); i--; } return false; }); });

我知道这是旧线程..我只想简单地分享增加id的方法。 我在所有克隆元素中使用相同的类

更新:

这种更优雅的方式:

 var clone_counter = 1; // global variable $('.clone').click(function(){ $('.clonethis').clone(); console.log(clone_counter); clone_counter++; }); 

我在其他地方发布了相同的答案 ,但在这里我认为它也适用于这个问题。

我创建了一个“原始”元素并将其隐藏在页面上。 我将“—”附加到需要在原始元素的任何子元素中递增的任何属性的值。

每当用户单击按钮创建原始克隆时,我创建了一个克隆,然后用该克隆的HTML中的当前索引全局替换“—”。 像这样的东西:

 var $clone = $original.clone(); var cloneHTML = $clone.html().replace(/---/g, incrementedFieldNum); $clone.html(cloneHTML); // Insert and show the clone after the original $original.after($clone); 

我使用data属性来存储incrementedFieldNum的更新值(未在上面的代码中显示)。

希望这会有所帮助。 这是一个很少的代码,我认为这是一个更通用的解决方案。 我有很多嵌套元素需要增加ID和名称,所以像@Fierceblood那样的解决方案是不切实际的。