How to move table row in jQuery?

前端 未结 2 397
眼角桃花
眼角桃花 2020-11-28 03:25

Say I had links with up/down arrows for moving a table row up or down in order. What would be the most straightforward way to move that row up or down one position (using jQ

相关标签:
2条回答
  • 2020-11-28 03:48
    $(document).ready(function () {
       $(".up,.down").click(function () {
          var $element = this;
          var row = $($element).parents("tr:first");
    
          if($(this).is('.up')){
             row.insertBefore(row.prev());
          } 
          else{
             row.insertAfter(row.next());
          }
    
      });
    

    });

    Try using JSFiddle

    0 讨论(0)
  • 2020-11-28 03:50

    You could also do something pretty simple with the adjustable up/down..

    given your links have a class of up or down you can wire this up in the click handler of the links. This is also under the assumption that the links are within each row of the grid.

    $(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());
            }
        });
    });
    

    HTML:

    <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>
    

    Demo - JsFiddle

    0 讨论(0)
提交回复
热议问题