Javascript jQuery 添加 <thead> 并添加 <tbody>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12781886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:14:44  来源:igfitidea点击:

jQuery add <thead> and add <tbody>

javascriptjquery

提问by Hello-World

How do I add <thead>and <tbody>this using jQuery?

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

the problem is my table has 1 or 2 th rows?

问题是我的表有第 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>

回答by epascarello

What you need to do is remove the rows and append them to a thead element

您需要做的是删除行并将它们附加到 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 exmaple?

jsFiddle 示例

回答by YogeshWaran

use wrapAll instead of wrap

使用 wrapAll 而不是 wrap

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

回答by Andrew Day

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);
}

Working version that creates a table from an array

从数组创建表的工作版本