防止JqueryUI中的列表项丢弃可排序

use*_*814 20 jquery drag-and-drop jquery-ui jquery-ui-sortable

我有两个列表 #sortable1,#sortable 2它们是连接的sortables,如本所示.

您可以将列表项拖放sortable1sortable 2.但是,如果sortable 1中的项目包含类"number",我想阻止Sortable2的删除,从而使拖动的项目回退到可排序的1.

我在sortable2上使用了以下内容:

receive: function (event, ui) {
            if ($(ui.item).hasClass("number")) {
                $(ui.item).remove();
            }
Run Code Online (Sandbox Code Playgroud)

但它会从两个表中删除列表项.任何帮助将不胜感激.

T J*_*T J 27

对于将来阅读此内容的人,正如briansol在对已接受答案的评论中所提到的那样,它会引发错误

Uncaught TypeError: Cannot read property 'removeChild' of null
Run Code Online (Sandbox Code Playgroud)

文档特别说

cancel()

取消当前可排序的更改并将其恢复为当前排序开始之前的状态.在停止接收回调函数中很有用.

在其他赛事取消的排序是不可靠的,所以最好使用receive如图事件MJ Azani答案或使用该stop事件,如下所示:

$('#list1').sortable({
  connectWith: 'ul',
  stop: function(ev, ui) {
    if(ui.item.hasClass("number"))
      $(this).sortable("cancel");
   }
}); 

$('#list2').sortable({
   connectWith: 'ul',
});  
Run Code Online (Sandbox Code Playgroud)

演示


Ric*_*ard 18

您可以使用beforeStopsortable('cancel')方法的组合来验证要移动的项目.在此示例中,在删除项目时,我通过以下方式检查项目是否有效:

  1. 检查项目是否有课程 number
  2. 检查列表项是否已被删除list2

这是我想要的稍微硬编码,所以或者你可以做的是检查被删除项目的父项this,以检查列表是否不同.这意味着您可能有一个numberin list1和的项目list2,但它们不可互换.

jsFiddle示例

$(function() {
    $('ul').sortable({
        connectWith: 'ul',
        beforeStop: function(ev, ui) {
            if ($(ui.item).hasClass('number') && $(ui.placeholder).parent()[0] != this) {
                $(this).sortable('cancel');
            }
        }
    });        
});?
Run Code Online (Sandbox Code Playgroud)

  • 使用这种方法,我似乎得到JS错误.我已经更新了jQUI网站上可能相关的错误报告.http://bugs.jqueryui.com/ticket/4904?cnum_edit=9#comment:9 (6认同)
  • 取消仅在 [this other answer](http://stackoverflow.com/a/24723176/133717) 中提到的 `stop` 和 `receive` 事件中是可靠的 (2认同)
  • 获取错误:未捕获TypeError:无法读取null的属性"removeChild".它打破了可分类...... (2认同)

Mj *_*ani 13

试试这个例子

$('#list1').sortable({
    connectWith: 'ul'
});    

$('#list2').sortable({
    connectWith: 'ul',
    receive: function(ev, ui) {
        if(ui.item.hasClass("number"))
          ui.sender.sortable("cancel");
    }
});