jquery - jquery sortable 在排序前删除下一行
问题描述
我有一张包含parent
和child
如下的表格。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
}
});
解决方案
要准确回答您的问题:
- 将下一个元素存储到
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>
推荐阅读
- react-native - 从 React-Native 应用程序在 Facebook 应用程序中分享 URL 作为帖子
- javascript - 在 Typescript 中,`return x` 和 `return await x` 之间有区别吗?
- r - 您可以为函数作为 R 中的随机样本进行论证吗?
- php - Spatie Laravel Jetstream 中的 id '#' 没有任何作用
- unity3d - 预制优化
- mysql - 如何使用 JSON_REPLACE 和 JSON_ARRAY 更改 MYSQL 数据库中 json 字段的数组值键?
- reactjs - 如何递归渲染菜单
- c# - 过滤时自动映射器映射异常
- sql - 具有多个值的 REGEXP_INSTR
- javascript - ios safari XMLHttpRequest jsonp 404