javascript - 反转HTML表格的行而不反转顶部

时间:2015-12-02 12:56:57

标签: javascript html css

我有一张表基本上是这样的:

a1 a2 a3

b1 b2 b3

c1 c2 c3

我想反转它,所以看起来像这样

c1 c2 c3

b1 b2 b3

a1 a2 a3

每当按下“click me”按钮时

<table class='standardtable'>
<tr>
   <th>Event</th>
   <th>Group</th>
   <th>Course</th>
   <th>Due Date</th>
   <th>Due In/<span class='red'>Late By</span></th>
  <button onclick="myFunction()">Click me</button>
</tr>
<td id='others'>
<?php
echo $html->tableCells($evalUpcoming);
?>
<?php if (empty($evalUpcoming)):?>
<tr><td colspan="5" align="center"><b> No peer evaluations due at this time </b></td></tr>
<?php endif; ?>
</td>

显然第一行是标题,其他是内容。我尝试使用td分离第一行和另一行,但它似乎不起作用:

<table class='standardtable'>
<tr>
   <th>Event</th>
   <th>Group</th>
   <th>Course</th>
   <th>Due Date</th>
   <th>Due In/<span class='red'>Late By</span></th>
  <button onclick="myFunction()">Click me</button>
</tr>
<td id='others'>
<?php
echo $html->tableCells($evalUpcoming);
?>
<?php if (empty($evalUpcoming)):?>
<tr><td colspan="5" align="center"><b> No peer evaluations due at this time </b></td></tr>
<?php endif; ?>
</td>
<script>
    function myFunction(){
        var table = document.getElementById('others');

        for (var i = 0; i < table.length; i++) {
            var rows = table[i].rows;
            for (var j = 0; j < rows.length; j++) {
                    rows[j].parentNode.insertBefore(rows[rows.length-1], rows[j]);
            }
        }
        }

    </script>

任何人都可以告诉我如何在不颠倒顶行的情况下扭转此表吗?

2 个答案:

答案 0 :(得分:1)

像这样构建你的表:

<table class='standardtable'>
<thead> <!-- use thead to separate headercontent -->
  <tr>
     <th>Event</th>
     <th>Group</th>
     <th>Course</th>
     <th>Due Date</th>
     <th>Due In/<span class='red'>Late By</span></th>
    <button onclick="myFunction()">Click me</button>
  </tr>
</thead>
<tbody> <!-- use tbody to separate tablecontent-->
  <?php
  echo $html->tableCells($evalUpcoming);
  ?>
  <?php if (empty($evalUpcoming)):?>
  <tr><td colspan="5" align="center"><b> No peer evaluations due at this time </b></td></tr>
  <?php endif; ?>
</tbody>

答案 1 :(得分:1)

我认为我的解决方案有点迟了但是,如果你通过使用thead和tbody分离你的元素,那么你将能够获得排序的分离,这样只有tbody的子元素才能获得排序

<table class='standardtable'>
  <thead>
    <tr>
       <th>Event</th>
       <th><button onclick="myFunction()">Click me</button></th>
    </tr>
  </thead>
  <tbody id="table-body">
    <tr>
      <td>a</td>
      <td></td>
    </tr>
    <tr>
      <td>b</td>
      <td></td>
    </tr>
    <tr>
      <td>c</td>
      <td></td>
    </tr>    
  </tbody>
</table>

以下是一个示例实现,它使用一种简单的方法来反转表体元素jsfiddle