JS克隆li容器内的空表tr

时间:2017-10-22 09:14:53

标签: javascript jquery clone

正如标题所说,我正在尝试克隆一个表格tr,但这应该在li容器内。

我的代码如下:

<ul>
<li class="menu-item">

    <table class="km-admin-table-repeated-field" width="100%">
    <thead>
        <tr>
            <th width="2%">Delete</th>
            <th width="2%">Sort</th>
            <th width="60%">URL</th>
            <th width="4%"></th>
        </tr>
    </thead>
    <tbody class="ui-sortable" style="">        

            <tr class="km-meta-box-row" style="">
                <td><a class="km-admin-button button remove-row" href="#">close</a></td>        
                <td><a class="km-admin-button sort button">sort</a></td>
                <td><input class="custom_media_url widefat" id="#" type="text" name="" value="#" placeholder="http://"></td>
                <td><input class="button custom_media_upload" id="km_field_image_upload_button" type="button" value="Upload Image"></td>
            </tr>           

    <!-- empty hidden one for jQuery // cloned field -->
    <tr class="km-meta-box-row km-empty-row screen-reader-text">
        <td><a class="km-admin-button button remove-row" href="#">close</a></td>        
        <td><a class="km-admin-button sort button">sort</a></td>
        <td><input id="km-image-button" class="widefat custom_media_url" type="text" name="#" placeholder="http://"></td>
        <td><input id="km-image-button km_field_image_upload_button" class="button custom_media_upload" type="button" value="Upload Image"></td>    
    </tr>

    </tbody>
    </table>

    <p><a class="button km-admin-button km-add-image" href="#">Add Image</a></p>

</li>
<li>...second li with the same code...</li>
</ul>

JS代码:

$('.km-add-image').on('click', function(e) {
    e.preventDefault();
    var row = $(this).parents('li.menu-item').find('.km-admin-table-repeated-field .km-empty-row.screen-reader-text').clone(true);
    row.removeClass('km-empty-row screen-reader-text');
    row.insertBefore('.km-admin-table-repeated-field tbody>tr:last');
    return false; 
});

JsFiddle:https://jsfiddle.net/kiarashi/31m9xLcr/

当我点击第一个add image内的li按钮时,会在第二个tr内添加空的li

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

你几乎就在那里。在这种情况下,您可能需要对插入新的<tr> html元素进行一些小的更改。

这是关于[将新表格行插入]到您的[table]

中的建议代码
$('.km-add-image').on('click', function(e) {
    e.preventDefault();

    // 1) Call the parent table's tbody
    var oMenuItem = $(this).parents('li.menu-item').find('.km-admin-table-repeated-field tbody');

    // 2) Then call the <tr> tag that have the 'km-meta-box-row' class
    // then clone it
    var row = oMenuItem.find('.km-meta-box-row').clone(true);
    row.removeClass('km-empty-row screen-reader-text');

    // 3) Then instead of 'inserting the new clone <tr>' before the last
    // empty row, We can append it inside the parent's tbody like this
    oMenuItem.append('<tr class="km-meta-box-row">' + row.html() + '</tr>');
    return false;

});

这里是上述代码给出的预期结果的jsfiddle。希望这能很好地指导你:https://jsfiddle.net/pdtxrmpt/2/