jQuery split a table into two tables at a particular row number

后端 未结 2 1268
广开言路
广开言路 2021-01-06 06:04

I need to split a table into two tables at a particular row number using jQuery. Can this be done?

I googled but couldn\'t find anything. jQuery\'s pretty powerful,

相关标签:
2条回答
  • 2021-01-06 06:27

    jQuery Slice method will be useful in such case: documentation here

    Add a table with some rows in html:

    <table id="mainTable">
    <tr>
        <td>Row 1</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 2</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 3</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 4</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 5</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 6</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 7</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 8</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 9</td>
        <td>Dummy Data</td>
    </tr>
    <tr>
        <td>Row 10</td>
        <td>Dummy Data</td>
    </tr>
    </table>
    

    Slice n rows using jQuery, create new table instance and append rows:

    <script type="text/javascript">
    jQuery(document).ready(function() {
        var $mainTable = $("#mainTable");
        var splitBy = 5;
        var rows = $mainTable.find ( "tr" ).slice( splitBy );
        var $secondTable = $("#mainTable").parent().append("<table id='secondTable'><tbody></tbody></table>");
        $secondTable.find("tbody").append(rows);
        $mainTable.find ( "tr" ).slice( splitBy ).remove();
    });
    </script>
    

    See working demo here

    0 讨论(0)
  • 2021-01-06 06:27

    This can also be done with clone()

    var $mainTable = $("table.mainTable");
    $mainTable.clone().appendTo($mainTable.parent()).find('tbody tr').slice(0, 4).remove();
    $mainTable.find('tbody tr').slice(4).remove();
    
    0 讨论(0)
提交回复
热议问题