【问题标题】:Move first row of a HTML table under a thead tag using JavaScript使用 JavaScript 将 HTML 表格的第一行移动到 thead 标记下
【发布时间】:2015-10-01 14:00:53
【问题描述】:

我有一个由 BIRT 生成的 html 表,如下所示:

<table id="myTableID">
    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>

    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>

    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</table>

我想编写一个 JavaScript 代码来读取该表并以以下形式重写它:在&lt;thead&gt; 标记中获取表的第一行,在&lt;tbody&gt; 标记中获取表的其余部分:

<table id="myTableID">
    <thead>
        <tr>
            <th></th>
            <th></th>
            <th></th> 
        </tr>
    </thead>

    <tbody>
        <tr>
            <th></th>
            <th></th>
            <th></th>
        </tr>

        <tr>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </tbody>    
</table>

我对 JavaScript 有基本的了解,但我不知道如何处理这种情况。请帮忙?

【问题讨论】:

  • $('#myTableID tr:first').wrap('&lt;thead /&gt;')
  • 基本上th 用于theadtd 用于tbody。 tbody 也需要th 吗?
  • 如果td 可以,请告诉我,我会发布我的答案..

标签: javascript jquery html birt


【解决方案1】:
  1. 使用prependTo() 插入thead 元素
  2. 使用append() 将第一个tr 插入到thead

$('<thead></thead>').prependTo('#myTableID').append($('#myTableID tr:first'));

console.log($('#myTableID')[0].outerHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table id="myTableID">
    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>

    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>

    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>
</table>

【讨论】:

  • @Dhoha,如果您运行 sn-p,它就可以工作。您能否详细说明为什么它不起作用,以便我提供帮助?您可以在 http:jsfiddle.net 中重现该尝试吗?
  • 抱歉,我又犯了一个错误,导致我无法看到结果……它奏效了 :)
  • @Dhoha,太棒了!很高兴它有帮助:)
猜你喜欢
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
  • 2018-05-01
  • 2013-12-19
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多