简体   繁体   English

如何在jQuery中移动表格行?

[英]How to move table row in jQuery?

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 jQuery)?将该行向上或向下移动一个位置的最直接方法是什么(使用 jQuery)?

There doesn't seem to be any direct way to do this using jQuery's built in methods, and after selecting the row with jQuery, I haven't found a way to then move it.使用 jQuery 的内置方法似乎没有任何直接的方法可以做到这一点,并且在使用 jQuery 选择行后,我还没有找到移动它的方法。 Also, in my case, making the rows draggable (which I have done with a plugin previously) isn't an option.此外,在我的情况下,使行可拖动(我以前使用插件完成)不是一个选项。

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.鉴于您的链接有一类updown您可以将其连接到链接的点击处理程序中。 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: 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演示 - JsFiddle

$(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尝试使用JSFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM