jQuery jQuery克隆一个新id的表,下面代码怎么统一写

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3752202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:02:17  来源:igfitidea点击:

jQuery to clone a table with new id, how to write below code collectively

jquery

提问by JustLearn

I'm having trouble with some jQuery stuff, please help me out. Below is my form structure:

我在处理一些 jQuery 东西时遇到了麻烦,请帮助我。以下是我的表单结构:

<form name="imageUploadForm" id="imageUploadForm" action="" method="POST" enctype="multipart/form-data" >
   <table border="0" width="80%" cellpadding="2" cellspacing="3" id="mainTable">
   <tbody>
    <tr>
            <td> 
                  <table border="0" id="imageTable" class="imageTable">
                    <tr>
                      <td><label for="image_title"><sup>*</sup>Image Title:</label></td>
                      <td><input type="text" name="image_title[]" id="image_title[]"></td>
                    </tr>
                    <tr>
                      <td><sup>*</sup>Image:</td>
                      <td><input type="file" name="main_image[]" id="main_image[]" ></td>
                    </tr>
                  </table>
            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td colspan="2"><input type="button" id="addRow" value="Add More" /></td>
        </tr>
    </tfoot>
    </table>    
</form> 

What I want is this: when I click on an Add More Button, a new table (i.e. clone of imagetable) appends to mainTable, here is my jQuery Code:

我想要的是:当我单击“添加更多”按钮时,一个新表(即 imagetable 的克隆)附加到 mainTable,这是我的 jQuery 代码:

jQuery(document).ready(function() {
    var count=1;
    jQuery('#addRow').click( function () {
        var Clonedtable = jQuery("#imageTable").clone(true);
        Clonedtable.appendTo('table#mainTable');
    })
});
  • I need to create different IDs for table, and the two inputs
  • Is it valid to make an array of IDs?
  • I want to append the cloned table append the tbody's last table, not just after the main ImageTable
  • Both inputs should be empty.
  • 我需要为表创建不同的 ID,以及两个输入
  • 制作一组 ID 是否有效?
  • 我想附加克隆表附加 tbody 的最后一个表,而不只是在主 ImageTable 之后
  • 两个输入都应为空。

Please suggest me optimized method. Thanks.

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



UPDATE:i have changed the table structure ( i was wrong before ), i want to change forattribute value of label according to next input id and delete <sup>*</sup>tag. i write below code, everything is working fine, but i need to write collectively, i don't understand how to write it collectively, please suggest me

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

 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');
    });

回答by user113716

EDIT:There are some issues with accessing properties of cloned elements. I changed the answer to use the native getAttributeand setAttributeinstead.

编辑:访问克隆元素的属性存在一些问题。我更改了答案以使用本机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 <td>
    clone.appendTo('#mainTable > tbody:last > td');
});?


Original answer:

原答案:

Try this:

尝试这个:

<script type="text/javascript">
    jQuery(document).ready(function() {
        jQuery('#addRow').click( function () {
                   // Get current count of imageTables and use that value for IDs
            var quantity = jQuery("table[id^=imageTable]").length;
                   // Clone the main table
            jQuery("#imageTable").clone(true)
                   // Change its ID to the current ID plus the quantity variable
                 .attr( 'id', function() { return this.id + quantity; })
                   // find any text or file inputs
                 .find( ':text,:file' )
                   // change their IDs
                 .attr( 'id', function() { return this.id + quantity; })
                   // set the input values to ""
                 .val( "" )
                   // return to the cloned table
                 .end()
                   // append wherever you want it.
                   // As the comment below your question states,
                   //   this is not a valid placement
                 .appendTo('#mainTable > tbody:last');
        })
    });
</script>

EDIT:Fixed typo in .find()where the comma was outside the quotation marks.

编辑:修复.find()了逗号在引号之外的拼写错误。

回答by Pramendra Gupta

if you want to keep simple change

如果你想保持简单的改变

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

回答by jessegavin

You're trying to append the cloned element to the wrong element, you're targeting table#mainTable, when you really want to append it to the tbody.

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

Change this line

改变这一行

Clonedtable.appendTo('table#mainTable');

To this

对此

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

But you really don't want to do that either. You really shouldn't have any tables directly in a tbody, but rather a tdelement.

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