使用jQuery将一个表格中选定的行数据复制到另一个表格

5

我有2个表格,其中一个包含我的产品数据,例如名称和条形码。 另一个表格为空,我想通过jQuery将产品表格(仅选择的行)复制到第二个表格中。

<table id="exampleTable1" style="max-width:50%;">
    <thead>
        <tr>
            <th>bar-code</th>
            <th>product name</th>
        </tr>
    </thead>
    <tbody>
        <tr role="row" class="odd selected">
            <td class="sorting_1">545333456</td>
            <td>Galaxy S9</td>
        </tr>
        <tr role="row" class="even selected">
            <td class="sorting_1">876543</td>
            <td>Galaxy S6</td>
        </tr>
        <tr role="row" class="odd">
            <td class="sorting_1">407654</td>
            <td>SD 64G </td>
        </tr>
        <tr role="row" class="even selected">
            <td class="sorting_1">876543</td>
            <td>Galaxy S5</td>
        <tr role="row" class="odd">
            <td class="sorting_1">407654</td>
            <td>Iphone 7 </td>
        </tr>
    </tbody>
</table>

我的第二个表格:

<table id="exampleTable2" style="max-width:50%;">
    <thead>
        <tr>
            <th>bar-code</th>
            <th>product name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
        </tr>
        <tr>
        </tr>
    </tbody>
</table>

<button class="btn btn-success" data-panelId="copy1" id="copy1">
    Copy from exampleTable1 To exampleTable1
</button>
1个回答

4

有几种jQuery方法可以轻松实现这一点,即 .clone().each() 方法。你可以通过以下方式实现你想要的:

$('#copy1').click(function() {

$('tr.selected', '#exampleTable1').each(function() {

    // For each "selected" row of table1 ..
    var rowFromTable1 = $(this);

    // .. Take a clone/copy of it ..
    var clonedRowFromTable1 = rowFromTable1.clone();

    // .. And append the cloned row to the tbody of table2
    $('tbody', '#exampleTable2').append( clonedRowFromTable1 )
 })

 })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接