2012-11-11 27 views
1

我想採取下面的元素HTML,並將其轉換爲下面的後元素HTML。如果使用thead和tfoot作爲post元素沒有任何意義,那麼tbody會起作用。我正在考慮從$('#myTable')開始,並用div封裝它。我正在努力如何最好地移除頁眉和頁腳,並將它們插入適當的表格中。感謝您的任何建議。使用jquery轉換表結構

預元素HTML:

<table id="myTable"> 
    <thead> 
     <tr> 
      <th>H1</th> 
      <th>H2</th> 
      <th>H3</th> 
     </tr> 
    </thead> 
    <tfoot> 
     <tr> 
      <th>F1</th> 
      <th>F2</th> 
      <th>F3</th> 
     </tr> 
    </tfoot> 
    <tbody> 
     <tr> 
      <th>B1</th> 
      <th>B2</th> 
      <th>B3</th> 
     </tr> 
    </tbody> 
</table> 

郵元素:

<div> 
    <table class="header"> 
     <thead> 
      <tr> 
       <th>H1</th> 
       <th>H2</th> 
       <th>H3</th> 
      </tr> 
     </thead> 
    </table> 
    <div> 
     <table id="myTable" class="body"> 
      <tbody> 
       <tr> 
        <th>B1</th> 
        <th>B2</th> 
        <th>B3</th> 
       </tr> 
      </tbody> 
     </table> 
    </div> 
    <table class="footer"> 
     <tfoot> 
      <tr> 
       <th>F1</th> 
       <th>F2</th> 
       <th>F3</th> 
      </tr> 
     </tfoot> 
    </table> 
</div> 
+0

的JavaScript不應該被用於固定標記。 – undefined

+0

爲什麼不呢?我的目的是修復標題,而CSS讓它變得困難。 – user1032531

+0

@undefined ..你能否詳細說明一下? :) – coolguy

回答

1

這裏:

var $table = $('#myTable').detach(); 

$('<div />').append(
    $('<table class="header" />').append($table.children('thead')), 
    $('<div />').append($table.addClass('body')), 
    $('<table class="footer" />').append($table.children('tfoot')) 
).appendTo('body'); 

現場演示:http://jsfiddle.net/MYbc6/4/

我明確地確定DOM操作操作的數量是最小化的,即表格從DOM分離,然後構建DIV,最後連接到DOM。

+0

一起工作並且謝謝Sime,並且不知道我得到了迴應。讓我看看它。謝謝! – user1032531

+0

我從來沒有用過detach()。看起來合適,但是,它看起來像它可能不會在原始#myTable相同的位置。 – user1032531

+1

@ user1032531嗯,我把DIV放在''中。您必須確保它與原始表的位置相同。這只是分離的缺點。 –

1

您應該選擇thead,tbody和tfoot並用div或表格將它們包裹起來。然後在tbody後面移動。

$table = $('#myTable'); 
$table.find('thead').wrap('<table class="header"></div>'); 
$table.find('tfoot').insertAfter($table.find('tbody')); 
$table.find('tfoot').wrap('<table class="footer"></div>'); 
$table.find('tbody').wrap('<div><table id="myTable" class="body"></table></div>'); 
$table.wrap('<div></div>').replaceWith($table.html()); 

演示:http://jsfiddle.net/F3MCv/2/

+0

你沒有達到預期的結構 - http://jsfiddle.net/F3MCv/1/(僅「標題」表在DIV,和「體」表不被包裹在第二DIV) –

+0

感謝對於通知。我編輯它在這裏和jsfiddle,輸出是現在所需的。 – halilb

+0

謝謝Halil,不知道我得到了回覆。讓我看看它。謝謝! – user1032531

0

我仍然不知道這是否是比任何上述兩大解決方案更好,但它是我在做什麼當前。 ŠimeVidas使用detach()可能更好,但我不知道如何在新位置重新插入修改過的HTML。

var $table = $('#myTable').addClass('body').wrap('<div />').wrap('<div />'); 
$table.parent() 
    .before($('<table class="header" />').append($table.children('thead'))) 
    .after($('<table class="footer" />').append($table.children('tfoot'))); 

演示:http://jsfiddle.net/zuHLX/