【问题标题】:Loop through each table row and swap two cells循环遍历每个表格行并交换两个单元格
【发布时间】:2021-05-13 06:21:03
【问题描述】:

这个问题可能有不同的答案,但不是我能找到的一种解决方案。

我有一个包含几行和单元格的表格。我需要将 cell2 的位置与 cell3 交换并且不更改任何内容。它可以工作,直到交换单元格。我只是错过了一些东西。

提前谢谢你!

<table id="myTable">
  <tr> 
    <td>1 APPLES</td>
    <td>3 ORANGES</td>
    <td>2 BANANAS</td>
    <td>4 GRAPES</td>
  </tr>
  <tr>
    <td>1 APPLES</td>
    <td>3 ORANGES</td>
    <td>2 BANANAS</td>
    <td>4 GRAPES</td>
  </tr>
  <tr>
    <td>1 APPLES</td>
    <td>3 ORANGES</td>
    <td>2 BANANAS</td>
    <td>4 GRAPES</td>
  </tr>
</table>

这是我的 jquery -- 尝试使用 .each()

$('table tbody tr').each(function () {    
    //make sure I found the rows
    $(this).css('border', '2px solid yellowgreen');
    
    //find the 2nd cell
    $(this).find('td:nth-child(2)').each(function () {
    
        //make it blue so I know the correct cell is found
        $(this).css('background', 'orange');

        //find the 2nd child in the current row
        $(this).find('td:nth-child(2)').each(function () {
            
            //change color to check correct cell    
            $(this).css('background','tan');    
            
            //move the 2nd cell after the 3rd cell -- swap places.
            $(this).insertAfter('td:nth-child(2)');
        });
    });

});

【问题讨论】:

    标签: jquery loops foreach


    【解决方案1】:

    实现这一点的一种方法是选择第三行中的所有td 并循环遍历它们,将它们移到上一个兄弟之前,如下所示:

    $('table tbody tr td:nth-child(3)').each(function() {
      let $td = $(this);
      $td.insertBefore($td.prev());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table id="myTable">
      <tr>
        <td>1 APPLES</td>
        <td>3 ORANGES</td>
        <td>2 BANANAS</td>
        <td>4 GRAPES</td>
      </tr>
      <tr>
        <td>1 APPLES</td>
        <td>3 ORANGES</td>
        <td>2 BANANAS</td>
        <td>4 GRAPES</td>
      </tr>
      <tr>
        <td>1 APPLES</td>
        <td>3 ORANGES</td>
        <td>2 BANANAS</td>
        <td>4 GRAPES</td>
      </tr>
    </table>

    您还可以使用其他组合,选择行中的第二个td 并使用insertAfter() 或next() 等,但上面概述的一般模式是相同的。

    但请注意,解决此问题的最佳方法是首先修复创建此 HTML 的输出。

    【讨论】:

    • 谢谢!!工作完美!!我想我太努力了,过度设计了它!出于某种原因,我觉得我需要找到该行,然后是第二个孩子并将其移到第三个孩子旁边。而不是找到 TD 的路径,然后交换位置
    • 没问题,很高兴为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2016-10-07
    相关资源
    最近更新 更多