2016-06-07 41 views
1

我有一个3列6行的表。我想将其中一些内容复制到新创建的列中,但将它们插入到中间。因此,它看起来像这样:复制多个TDS

enter image description here

有了这个aprroach:

$("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(); 
    $newRow.append($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(); 
    $newRow.append($newCell); 
}); 

我得到的结果是:

enter image description here

所以新列应之间插入非常左列,并与Abc列,而不是在正确的。

FIDDLE

回答

1

要在表格中间插入一些东西,可以使用before()after()。例如,我们要插入我们的Abc项目之前,新的细胞,从而代替将它结束时,您可以使用下面的代码Abc前插入它(是最后td)的:

// Find the last element, and add the new cell before it. 
$newRow.find("td:last").before($newCell); 

Fiddle Here


如果您想要更具体一些,可以通过选择器中的文本指定元素。因此,在这种情况下,您可以在包含文字td的元素之前声明'Abc'

$newRow.find("td:contains('Abc')").before($newCell);