如何用jQuery拆分表行(在TD之间插入TR)

时间:2015-02-03 13:35:51

标签: jquery html-table

我在使用jQuery拆分表时遇到了一些问题。

这是表格:

<table width="100%" id="submenu">
    <tr>
        <td class="submenu">A</td>
        <td class="submenu">B</td>
        <td class="submenu">C</td>
        <td class="submenu">D</td>
        <td class="submenu">E</td>
        <td class="submenu">F</td>  
        <td class="submenu">G</td>     
        <td class="submenu">H</td>        
    </tr>
</table>

我想在调用函数后让它看起来像这样:

<table width="100%" id="submenu">
    <tr>
        <td class="submenu">A</td>
        <td class="submenu">B</td>
        <td class="submenu">C</td>
        <td class="submenu">D</td>
    </tr>
    <tr>
        <td class="submenu">E</td>
        <td class="submenu">F</td>  
        <td class="submenu">G</td>     
        <td class="submenu">H</td>        
    </tr>
</table>

我尝试过:

$(function(){
    $('.submenu td:eq(3)').after('</tr><tr>');
});

3 个答案:

答案 0 :(得分:3)

请尝试使用此代码段:

&#13;
&#13;
$(function(){
  // # Add a new row after the first one in the table
  $('table#submenu tr:first').after('<tr></tr>');

  // # Move the four last TDs to this new row
  $('table#submenu tr:first td.submenu:gt(3)') // Select the four last TDs
   .detach() // Detach them from their current row
   .appendTo('table#submenu tr:nth-child(2)'); // Add them at the end of the new row
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table width="100%" id="submenu" border="1">
    <tr>
        <td class="submenu">A</td>
        <td class="submenu">B</td>
        <td class="submenu">C</td>
        <td class="submenu">D</td>
        <td class="submenu">E</td>
        <td class="submenu">F</td>  
        <td class="submenu">G</td>     
        <td class="submenu">H</td>        
    </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

<script>
     $(".submenu td:nth-child(4)" ).after( "</tr><tr>" );
</script>

这样可行。

答案 2 :(得分:0)

此代码解决了您的问题。

enter image description here

$(document).ready(function(){  
     $("table tr td:nth-child(5n)").addClass('break');
    var boundary = $("td.break");
    $("<tr>").insertAfter(boundary.parent()).append(boundary.nextAll().andSelf());
});

DEMO