2013-11-25 39 views
1

我有一個表:在jQuery中複製元素和父母?

<table> 
    <thead> 
     <th></th> 
     <th>Col 1</th> 
     <th>Col 2</th> 
    </thead> 

    <tbody> 
     <tr> 
      <th>R1</th> 
      <td>Data</td> 
      <td>Data</td> 
     </tr> 
     <tr> 
      <th>R2</th> 
      <td>Data</td> 
      <td>Data</td> 
     </tr> 
     <tr> 
      <th>R3</th> 
      <td>Data</td> 
      <td>Data</td> 
     </tr> 
    </tbody> 
</table> 

我想複製所有th和他們的父母(從tr高達table)。預期結果應該是:

<table> 
    <thead> 
     <th></th> 
     <th>Col 1</th> 
     <th>Col 2</th> 
    </thead> 

    <tbody> 
     <tr> 
      <th>R1</th> 
     </tr> 
     <tr> 
      <th>R2</th> 
     </tr> 
     <tr> 
      <th>R3</th> 
     </tr> 
    </tbody> 
</table> 

正如你所看到的,我複製一切,除了td的。

我可以通過一步一步的方式做到這一點(首先table,然後thead,等等)。 jQuery中是否有一個選擇器可以在一行中完成我想要的功能?

回答

1

我會克隆整個table,然後刪除所有td S和追加回到它body

var tab = $('table').clone(); 
tab.find('td').remove(); 
tab.appendTo('body'); 

入住這fiddle

+0

這樣做,有沒有更有效的方法來做到這一點? – dpp

+0

@dpp我不認爲有比這更好的方法,無論如何讓我們等待其他答案。 – Praveen