use*_*330 8 html javascript jquery
我有一张这样的桌子:
<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>
Run Code Online (Sandbox Code Playgroud)
如何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>
Run Code Online (Sandbox Code Playgroud)
这是我的方法,不起作用:
$("table td:nth-child(2)[id$=2]").after("table td:nth-child(2)");
Run Code Online (Sandbox Code Playgroud)
实现您想要的目标的一种方法:
// 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));
}
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)