在表行重新排序中显示向上/向下按钮

时间:2016-07-06 19:29:13

标签: javascript jquery html css

我正在使用这个jsfiddle:http://jsfiddle.net/vaDkF/828/ (没有顶部和底部选项)来创建重新排序表。



$(document).ready(function(){
    $(".up,.down").click(function(){
        var row = $(this).parents("tr:first");
        if ($(this).is(".up")) {
            row.insertBefore(row.prev());
        } else  {
            row.insertAfter(row.next());
        } 
       
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>One</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Two</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Three</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Four</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
    <tr>
        <td>Five</td>
        <td>
            <a href="#" class="up">Up</a>
            <a href="#" class="down">Down</a>
        </td>
    </tr>
</table>
&#13;
&#13;
&#13;

我想知道如果它是表格中的第一行,是否可以让向上按钮消失(显示无),如果它是表格中的最后一行,则向下按钮消失。

谢谢!

1 个答案:

答案 0 :(得分:6)

您可以使用CSS,first-childlast-child选择器:

tr:first-child .up, tr:last-child .down {
  display:none;
}

&#13;
&#13;
$(document).ready(function() {
  $(".up,.down").click(function() {
    var row = $(this).parents("tr:first");
    if ($(this).is(".up")) {
      row.insertBefore(row.prev());
    } else {
      row.insertAfter(row.next());
    }
  });
});
&#13;
tr:first-child .up,
tr:last-child .down {
  display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>One</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Two</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Three</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Four</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
  <tr>
    <td>Five</td>
    <td>
      <a href="#" class="up">Up</a>
      <a href="#" class="down">Down</a>
    </td>
  </tr>
</table>
&#13;
&#13;
&#13;

Updated Demo