jQuery用新的id克隆一个表,如何集体写下面的代码

我遇到一些jQuery的问题,请帮帮我。 以下是我的表单结构:

*Image:

我想要的是:当我点击Add More按钮时,一个新表(即imagetable的克隆)附加到mainTable,这是我的jQuery代码:

 jQuery(document).ready(function() { var count=1; jQuery('#addRow').click( function () { var Clonedtable = jQuery("#imageTable").clone(true); Clonedtable.appendTo('table#mainTable'); }) }); 
  • 我需要为表和两个输入创建不同的ID
  • 制作一系列ID是否有效?
  • 我想追加克隆表附加tbody的最后一个表,而不仅仅是在主ImageTable之后
  • 两个输入都应为空。

请建议我优化的方法。 谢谢。


更新:我已经更改了表结构(之前我错了),我想根据下一个输入id更改label的属性值并删除*标签。 我写下面的代码,一切正常,但我需要集体写,我不明白如何写它集体,请建议我

  jQuery('#addRow').live('click', function () { var quantity = jQuery('table[class^=imageTable]').length; var clonedRow = jQuery('#mainTable > tbody > tr:first').clone(true); var textID = clonedRow.find(':text').attr('id'); clonedRow.find('label').attr('for', function () { return textID + quantity; }); clonedRow.find('th').text('Image '+(++quantity) + ' :'); clonedRow.find('sup').remove(); clonedRow.attr('id', function () { return this.id + quantity; }).find(':text,:file').attr('id', function () { return this.id + quantity; }).val('').end().appendTo('#mainTable'); }); 

编辑:访问克隆元素的属性存在一些问题。 我更改了答案以使用本机getAttributesetAttribute

 jQuery('#addRow').click(function() { // Get current count of imageTables and use that value for IDs var quantity = jQuery("table[id^=imageTable]").length; // clone the table var clone = jQuery("#imageTable").clone(true); // use native DOM methods to update the ID clone[0].setAttribute('id', clone[0].getAttribute('id') + quantity); // find any text or file inputs, and iterate over them clone.find(':text,:file').each(function() { // use native DOM methods to update the ID this.setAttribute('id', this.getAttribute('id') + quantity); // set the value to "" this.value = ""; }); // append to the  clone.appendTo('#mainTable > tbody:last > td'); });​ 

原始答案:

试试这个:

  

编辑:修复.find()中的错误,其中逗号在引号之外。

如果你想保持简单的改变

  var table= $(".imageTable").html(); table.appendTo("#mainTable"); 

你试图将克隆的元素附加到错误的元素,当你真的想将它附加到tbody时,你的目标是table#mainTable

改变这一行

 Clonedtable.appendTo('table#mainTable'); 

对此

 Clonedtable.appendTo('table#mainTable tbody'); 

但你真的不想这样做。 你真的不应该直接在tbody有任何表,而是一个td元素。