首页 > 解决方案 > jquery sortable 在排序前删除下一行

问题描述

我有一张包含parentchild如下的表格。parent是可排序的。当我尝试对任何父母进行排序时,我必须将其删除,child然后将其插入到新位置之后。

<table>
    <tr class="parent"><td>Parent1</td></tr>
    <tr class="child nosort"><td>Child1</td></tr>
    <tr class="parent"><td>Parent2</td></tr>
    <tr class="child nosort"><td>Child2</td></tr>
    <tr class="parent"><td>Parent3</td></tr>
    <tr class="child nosort"><td>Child3</td></tr>
</table>

因此,如果我在 Parent2 之后移动 Parent1,它将看起来:

<table>       
    <tr class="parent"><td>Parent2</td></tr>
    <tr class="child nosort"><td>Child2</td></tr>
    <tr class="parent"><td>Parent1</td></tr>
    <tr class="child nosort"><td>Child1</td></tr>
    <tr class="parent"><td>Parent3</td></tr>
    <tr class="child nosort"><td>Child3</td></tr>
</table>

我已经完成了子元素的插入,sortupdate但无法弄清楚如何在排序之前删除子行。下面如果代码写在start.

$('table').sortable({
    items: 'tr:not(.nosort)',
    start: function( event, ui ) {
        // Removal code of child before sort
        var objChild = ui.item.next();
        if( objChild.hasClass('child') ) {
            objChild.remove();
        }
    },
    update: function( event, ui ) {
    //  insertion code of child
    }
});

标签: jqueryjquery-ui-sortable

解决方案


准确回答您的问题:

  • 将下一个元素存储到data-*每个元素的属性中.parent
  • 在可排序start事件上,使用jQuery.detach()将子元素存储到数据中。
  • 在可排序stop事件上使用.after()ti 插入先前分离的元素

$('.parent').each(function(i, e) {
   $(this).data('$next', $(this).nextUntil('.parent'));
});

$('table').sortable({
  items: 'tr:not(.nosort)',
  start: function( ev, ui ) {
    $next = $(ui.item.data('$next')).detach();    
  },
  stop: function(event, ui) {
    ui.item.after($next);
  }
});
<table>
  <tr class="parent"><td>1 Parent</td></tr>
  <tr class="child nosort"><td>1 Child</td></tr>
  <tr class="parent"><td>2 Parent</td></tr>
  <tr class="child nosort"><td>2 Child</td></tr>
  <tr class="parent"><td>3 Parent</td></tr>
  <tr class="child nosort"><td>3 Child</td></tr>
</table>

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

但如您所知,您最终也可能拥有 P2 P1 C1 C2 ...但这不是您的问题。否则,要解决这个问题,最好的办法就是回到白板上,简单地将两个<div>s 放在一个<td>


推荐阅读