我有一个包含 2-4 列和 9 行的表格。一些最右边的列有文本 (abc),一些有图像,一些两者都有,有些可能两者都没有。
我想将第 2 列的内容复制到 3 个新创建的列中,但将它们插入中间(在 abc
和图像之前,如果适用)。所以它看起来像这样:
这种方法:
$("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);
}
});
产生以下结果:
FIDDLE .
最佳答案
要实现此目的,您可以使用 :nth-child
遍历每第三行,将每一行所需的 td
附加到集合中的第一行。从那里你可以 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();
关于javascript - 将多个 TD 插入表的中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720558/