首页 > 解决方案 > 循环遍历每个表格行并交换两个单元格

问题描述

这个问题可能已经以不同的方式得到了回答,但不是我能找到的一种解决方案。

我有一个包含几行和单元格的表格。我需要将 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)');
        });
    });

});

标签: jqueryloopsforeach

解决方案


实现此目的的一种方法是选择td第 3 行中的所有元素并循环遍历它们,将它们移动到它们之前的兄弟元素之前,如下所示:

$('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(), ornext()等​​,但上面概述的一般模式是相同的。

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


推荐阅读