【问题标题】:How to split a table row with jQuery (insert TR between TD's)如何使用 jQuery 拆分表格行(在 TD 之间插入 TR)
【发布时间】:2017-01-02 03:00:50
【问题描述】:

我在使用 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>');
});

【问题讨论】:

  • 为什么在编写/生成 HTML 时不创建两行表?这不是 jQuery 的任务(根本不是 JavaScript)
  • @panther 因为如果您想在页面加载后更改页面内容,Javascript 是您唯一的选择。

标签: jquery html-table


【解决方案1】:

试试这个 sn-p:

$(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
});
<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>

【讨论】:

    【解决方案2】:
    <script>
         $(".submenu td:nth-child(4)" ).after( "</tr><tr>" );
    </script>
    

    这会起作用。

    【讨论】:

      【解决方案3】:

      这段代码解决了你的问题。

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

      DEMO

      【讨论】:

        猜你喜欢
        • 2014-03-10
        • 2021-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多