簡體   English   中英

jQuery 添加<thead>並添加<tbody>

[英]jQuery add <thead> and add <tbody>

如何使用 jQuery 添加<thead><tbody>

問題是我的表有第 1 行或第 2 行?

$('#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>

您需要做的是刪除行並將它們附加到 thead 元素

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 示例

使用 wrapAll 而不是 wrap

$('#myTable tr:has(th)').wrapAll('<thead></thead>');​
$("#myTable thead").prependTo("#myTable")
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);
}

從數組創建表的工作版本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM