divide a table
divide a table
I want to divide a table to two new table, this is my way, and hope the code can be more brief.
Script
- $(function() {
- var $devide = 2,
- $newTableWidth1 = 0,
- $newTableWidth2 = 0,
- $newTableStr1 = '<table id="newTable1">',
- $newTableStr2 = '<table id="newTable2">';
-
- $('table tr').each(function($i) {
- $newTableStr1 += $(this).is('[class]') ? '<tr class="' + $(this).attr('class') + '">' : '<tr>';
- $newTableStr2 += $(this).is('[class]') ? '<tr class="' + $(this).attr('class') + '">' : '<tr>';
- $(this).find('td').each(function() {
- // get new table 1 width
- if ($i == 0) {
- if ($(this).index() < $devide) {
- $newTableWidth1 += $(this).outerWidth();
- } else {
- $newTableWidth2 += $(this).outerWidth();
- }
- }
-
- // new table 1
- if ($(this).index() < $devide) {
- $newTableStr1 += $(this).is('[class]') ? '<td class="' + $(this).attr('class') + '">' + $(this).html() + '</td>' : '<td>' + $(this).html() + '</td>';
- } else {
- $newTableStr2 += $(this).is('[class]') ? '<td class="' + $(this).attr('class') + '">' + $(this).html() + '</td>' : '<td>' + $(this).html() + '</td>';
- }
- });
- $newTableStr1 += '</tr>';
- $newTableStr2 += '</tr>';
- });
-
- $newTableStr1 += '</table>';
- $newTableStr2 += '</table>';
-
- $('body').append($newTableStr1).append($newTableStr2);
- $('#newTable1').width($newTableWidth1);
- $('#newTable2').width($newTableWidth2);
- });
CSS
- <style>
- body {
- font-size: 12px;
- }
- table {
- border-collapse: collapse;
- margin: 4px 0;
- }
- tr, td {
- text-align: center;
- border: 1px solid black;
- }
- td {
- padding: 4px;
- }
- .yellow {
- background: yellow;
- }
- .gray {
- background: gray;
- }
- </style>
HTML
- <table width="400" border="0" cellspacing="0" cellpadding="0">
- <tr>
- <td>a</td>
- <td>b</td>
- <td>c</td>
- <td>d</td>
- <td>e</td>
- </tr>
- <tr>
- <td>1</td>
- <td>2</td>
- <td class="gray">3</td>
- <td>4</td>
- <td>5</td>
- </tr>
- <tr class="yellow">
- <td>6</td>
- <td>7</td>
- <td>8</td>
- <td>9</td>
- <td>10</td>
- </tr>
- <tr>
- <td>11</td>
- <td class="gray">12</td>
- <td>13</td>
- <td>14</td>
- <td>15</td>
- </tr>
- <tr>
- <td>16</td>
- <td>17</td>
- <td>18</td>
- <td>19</td>
- <td>20</td>
- </tr>
- </table>