我有一张这样的 table :
<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
</tr>
<tr>
<td>some column|2</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|2</td>
<td id="def|2">def</td>
</tr>
</table>
如何将带有后缀
tds
的|2
移到右侧,从而添加第3列?另外,应将剩余的“空” td“某些列| 2”和“另一列| 2”完全删除。最终结果应如下所示:
这是所需的代码:
<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
<td id="def|2">def</td>
</tr>
</table>
这是我的方法,不起作用:
$("table td:nth-child(2)[id$=2]").after("table td:nth-child(2)");
FIDDLE。
最佳答案
一种实现所需目标的方法:
// Values for new column to be added
var newVals = $("table td:nth-child(2)[id$=2]");
$("table td:nth-child(2)[id$=1]").each(function (ind) {
if (ind < newVals.length) {
// Get New Element to add
var newElement = newVals[ind];
// Remove original row for this element
$(newElement).parent().remove();
// Append to new column
$(this).after($(newElement));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>some column|1</td>
<td id="abc|1">abc</td>
</tr>
<tr>
<td>another column|1</td>
<td id="def|1">def</td>
</tr>
<tr>
<td>ome column|2</td>
<td id="abc|2">abc</td>
</tr>
<tr>
<td>another column|2</td>
<td id="def|2">def</td>
</tr>
</table>
关于javascript - 将td移到新列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37594430/