2016-06-07 53 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);