[英]Insert multiple TDs into middle of Table
I have a table with 2-4 columns and 9 rows. 我有一张2-4列和9行的表格。 Some of the very right columns have a text (abc), some have an image, some have both and some may have neither of them.
一些最右边的列具有文本(abc),一些具有图像,一些具有两者,而某些可能都不具有。
I want to copy the contents of the 2nd column into 3 newly created columns, but insert them in the middle (before abc
and the image, if applicable). 我想将第二列的内容复制到3个新创建的列中,但将它们插入中间(在
abc
和图像之前,如果适用)。 So that it looks like that: 这样看起来像:
This approach: 这种方法:
$("table td:nth-child(2) [id$=2]").each(function(i) {
var $newCell = $(this).wrap('<td></td>').parent();
var $newRow = $("table td:nth-child(2) [id$=1]").eq(i).parents('tr');
$(this).parents('tr').remove();
if ($newRow.find("td:contains('abc')").index() > -1) {
$newRow.find("td:contains('abc')").before($newCell);
} else if ($newRow.find("td.img").index() > -1) {
$newRow.find("td:contains('img')").before($newCell);
} else {
$newRow.find("td:contains('img')").before($newCell);
}
});
$("table td:nth-child(2) [id$=3]").each(function(i) {
var $newCell = $(this).wrap('<td></td>').parent();
var $newRow = $("table td:nth-child(2) [id$=1]").eq(i).parents('tr');
$(this).parents('tr').remove();
if ($newRow.find("td:contains('abc')").index() > -1) {
$newRow.find("td:contains('abc')").before($newCell);
} else if ($newRow.find("td.img").index() > -1) {
$newRow.find("td:contains('img')").before($newCell);
} else {
$newRow.find("td:contains('img')").before($newCell);
}
});
Produces the following result: 产生以下结果:
To achieve this you can loop over each third row using :nth-child
, appending the required td
from each to the first row in the set. 为此,您可以使用
:nth-child
遍历第三行,将每行所需的td
追加到集合中的第一行。 From there you can remove()
the unneeded rows, something like this: 从那里可以
remove()
不需要的行,如下所示:
for (var i = 0; i < $('table tr').length / 3; i++) {
var $rows = $('table tr:nth-child(3n+' + i + ')');
$rows.not(':first').addClass('remove').find('td:eq(1)').insertAfter($rows.first().find('td:eq(1)'));
}
$('table .remove').remove();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.