jquery - 循环遍历每个表格行并交换两个单元格
问题描述
这个问题可能已经以不同的方式得到了回答,但不是我能找到的一种解决方案。
我有一个包含几行和单元格的表格。我需要将 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)');
});
});
});
解决方案
实现此目的的一种方法是选择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 的输出。
推荐阅读
- python - 计算python pandas中的差异时值不正确
- flutter - “MqttMessage”类型的值不能分配给“MqttPublishMessage”类型的变量
- python - 斐波那契数列:寻找复合问题
- google-sheets - 如何在 Google 表格的 Query/ImportRange 函数的开头添加一列?
- python - 如何使用 .apply() 解决 pandas 广播错误?
- java - google reCaptcha 端点有多少个 HTTPS 证书?我在哪里可以下载它们?
- reactjs - 组件定义缺少 forwardRef 的显示名称
- date - 如何从特定小时范围内的行中选择最小值?
- set - 当滑块用于其他任务时保持原始滑块值
- apache-kafka - SpringBoot 批量监听模式 vs 非批量监听模式