如何沿自动排列行号的方向上下排列表格行



HTML:

<table class="myTable" border="1" width="80%">
  <tr >
    <td></td>
    <td>one</td>
    <td><button onClick="MoveUp();">&#8679;</button></td>
    <td><button onClick="MoveDown();">&#8681;</button></td>
  </tr>
  <tr>
    <td></td>
    <td>two</td> 
    <td><button onClick="MoveUp();">&#8679;</button></td>
    <td><button onClick="MoveDown();">&#8681;</button></td>
  </tr>
  <tr>
    <td></td>
    <td>three</td> 
    <td><button onClick="MoveUp();">&#8679;</button></td>
    <td><button onClick="MoveDown();">&#8681;</button></td>
  </tr>
  <tr>
    <td></td>
    <td>four</td> 
    <td><button onClick="MoveUp();">&#8679;</button></td>
    <td><button onClick="MoveDown();">&#8681;</button></td>
  </tr>
  <tr>
    <td></td>
    <td>five</td> 
    <td><button onClick="MoveUp();">&#8679;</button></td>
    <td><button onClick="MoveDown();">&#8681;</button></td>
  </tr>
</table>

CSS:

 table.myTable {
     counter-reset: rowNumber;
 }
 table.myTable tr {
     counter-increment: rowNumber;
 }
 table.myTable tr td:first-child::before {
     content: counter(rowNumber);
     min-width: 1em;
     margin-right: 0.5em;
 }

JavaScript:

 function MoveUp() {
     var tablebody = document.getElementById('mytable'); 
     if(TableLocation > 0) { 
         tablebody.moveRow(TableLocation, TableLocation - 1);
         TableLocation = TableLocation - 1;
     }
 }
 function MoveDown() {
     var tablebody = document.getElementById('mytable'); 
     if((TableLocation > 0) && (TableLocation < tablebody.rows.length - 1)) { 
         tablebody.moveRow(TableLocation, TableLocation + 1);
         TableLocation = TableLocation + 1;
     }
 }

我正在从后端获取表数据,并从css添加行号。我使用JavaScript来上下移动行。它不起作用。如果发生向上和向下移动行的情况,则必须自动将行号从一排到最后一排。

这是我的小提琴。

工作版本

您必须找到按钮的父tr,然后找到之前要附加的元素。因为没有在一个元素后面追加的函数,所以当你想向下移动时,你必须找到下一个元素。

上移功能:

function MoveUp() {
    var table,
        row = this.parentNode;
    // find the parent tr ( the row element )
    while ( row != null ) {
        if ( row.nodeName == 'TR' ) {
            break;
        }
        row = row.parentNode;
    }
    // the parent of the row is the table body
    table = row.parentNode;
    // insert the row before it's previevs siblings
    table.insertBefore ( row, get_previoussibling( row ) );
}

下移功能:

function MoveDown() {
    var table,
        row = this.parentNode;
    while ( row != null ) {
        if ( row.nodeName == 'TR' ) {
            break;
        }
        row = row.parentNode;
    }
    table = row.parentNode;
    // you have to find the second next siblings to append before
    // NOTE: if the second parameter of the 'insertBefore' function is null
    //       it will append the row to the table! 
    table.insertBefore ( row, get_nextsibling ( get_nextsibling( row ) ) );
}

最新更新