2012-10-08 10 views
5

Wie füge ich <thead> und <tbody> dies mit jquery?jquery add <thead> und <tbody> hinzufügen

das Problem ist meine Tabelle hat 1 oder 2 Zeilen?

$('#myTable tr:has(th)').wrap('<thead></thead>'); 

<table id="myTable"> 

<tr><th>1</th><th>2</th><th>3</th><th>4</th></tr> 
<tr><th>1</th><th>2</th><th>3</th><th>4</th></tr> 

<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr> 
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr> 
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr> 
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr> 
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr> 



</table> 
+2

a [Tabellenkopf] (http://www.w3.org/wiki/HTML/Elements/th) hat in der Regel ein 'thead' Element als ein Geschwister von 'tbody', nicht mehrere Köpfe in einer Reihe. – jbabey

+0

@jbabey Nicht jeder Browser fügt ein thead-Element hinzu. Sie fügen einen tbody hinzu. – epascarello

Antwort

13

Was Sie tun müssen, ist die Zeilen zu entfernen und hängen Sie sie an einem thead Element

var myTable = jQuery("#myTable"); 
var thead = myTable.find("thead"); 
var thRows = myTable.find("tr:has(th)"); 

if (thead.length===0){ //if there is no thead element, add one. 
    thead = jQuery("<thead></thead>").appendTo(myTable);  
} 

var copy = thRows.clone(true).appendTo("thead"); 
thRows.remove(); 

jsFiddle exmaple

5

Verwendung wrapAll statt Wrap

$('#myTable tr:has(th)').wrapAll('<thead></thead>');​ 
$("#myTable thead").prependTo("#myTable") 
+1

Das ist falsch. Es wird ' – epascarello

+1

[jsFiddle] (http://jsfiddle.net/q224z/) zeigt diese gebrochen ist und eine falsche Lösung in' führen. – epascarello

+0

versuchen Sie wrapAll (''); – AlxVallejo

0
function createTable(data) { 
    var str = ""; 
    str += '<table><thead>'; 
    str += '<tr><td>Pos</td><td>Ref</td></tr></thead><tbody>'; 
    for (var item in data.recentList) { 
     str += '<tr>'; 
     for (idata in data.recentList[item]) { 
      str += '<td>' + data.recentList[item][idata] + '</td>'; 
     } 
     str += '</tr>'; 
    } 
    str += '</tbody></table>'; 
    $('body').append(str); 
} 

Arbeitsversion, die eine Tabelle aus einem Array erzeugt