jQuery将thead添加到表中

时间:2016-06-13 17:22:38

标签: javascript jquery

我正在使用MyFaces Trinidad JSF框架,它创建了tr:table,如下所示:

<table id="myTable">
    <tbody>
        <tr>
            <th>1</th>
            <th>2</th>
            <th>3</th>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
    </tbody>
</table>

我需要以下一个来实现可滚动标头。所以我想尝试使用jQuery

转换它们
<table id="myTable">
    <thead>
        <tr>
            <th>1</th>
            <th>2</th>
            <th>3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
        <tr>
            <td>1</td>
            <td>2</td>
            <td>3</td>
        </tr>
    </tbody>
</table>

我已经尝试了thisthis个答案,但没有一个能解决我的问题。

2 个答案:

答案 0 :(得分:1)

thead换行第一行并附加在表的开头

&#13;
&#13;
$('#myTable tbody tr:first') // get first row
  //.detach() // remove from table, it's optional to detach
  .wrap('<thead/>') // wrap with tbody
  .parent() // get tbody 
  .prependTo('#myTable') // append at the beginning
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tbody>
  <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>
</tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你可以使用

"SMTPD" 5444    65  "2016-06-13 19:12:43.491"   "127.0.0.1" "RECEIVED: MAIL FROM:<test@localhost.com>"
"SMTPD" 5444    65  "2016-06-13 19:12:43.497"   "127.0.0.1" "SENT: 250 OK"
"SMTPD" 4120    65  "2016-06-13 19:12:43.498"   "127.0.0.1" "RECEIVED: RCPT TO:<run@gmail.com>"
"SMTPD" 4120    65  "2016-06-13 19:12:43.503"   "127.0.0.1" "SENT: 250 OK"
"SMTPD" 8080    65  "2016-06-13 19:12:43.504"   "127.0.0.1" "RECEIVED: DATA"
"SMTPD" 8080    65  "2016-06-13 19:12:43.542"   "127.0.0.1" "SENT: 354 OK, send."
"SMTPD" 3144    65  "2016-06-13 19:12:43.626"   "127.0.0.1" "SENT: 250 Queued (0.080 seconds)"
"SMTPD" 4120    65  "2016-06-13 19:12:43.628"   "127.0.0.1" "RECEIVED: QUIT"
"SMTPD" 4120    65  "2016-06-13 19:12:43.629"   "127.0.0.1" "SENT: 221 goodbye"

// append the first row to thead and prepend thead to #mytable
$('<thead></thead>').append($('tbody > tr:nth-child(1)')).prependTo('#myTable');
// remove the first row from tbody
$('#myTable > tbody > tr:nth-child(1)').remove();
// append the first row to thead and prepend thead to #mytable
$('<thead></thead>').append($('tbody > tr:nth-child(1)')).prependTo('#myTable');
// remove the first row from tbody
$('#myTable > tbody > tr:nth-child(1)').remove();