如何区分在同一列表中拖动和从一个列表移动到连接列表时的可排序更新事件

How to differentiate between the sortable update events when dragging within the same list and when moving from one list to a connected list

本文关键字:列表 连接 移动 一个 更新 排序 事件 何区 拖动      更新时间:2023-09-26

我有两个连接的可排序列表,#origin#destination。当您从#origin拖放到#destination时,我可以看到以下事件按此顺序发生:

  1. #origin更新
  2. #origin移除
  3. #destination接收
  4. #destination更新

但是,当在#origin列表中拖放时,仅执行#origin更新功能。

问题是,当执行#origin更新时,它看起来与在同一列表中拖放时完全相同。在这两种情况下,ui.sender都没有设置,并且由于它是在执行remove函数之前执行的,所以我无法设置临时变量来说明发生了什么。

(看这个Fiddle,看看控制台(

我想在更新函数中包含一个ajax调用,而不需要执行两次。因此,我需要一种方法来区分从一个列表拖动到另一个列表时调用的#origin更新(因此我基本上只能使用return false(和在同一列表中拖动时调用的更新。

我想得到ui.position并检查该坐标是否在#origin的边界内,但似乎必须有一个更简单的解决方案。

这里有一种方法:为每组、起点和终点设置一个标志。在sortable上初始化它,如下所示:

var updates={origin:false,destination:false};
$( ".config-room-ul" ).sortable({//...

在更新方法中,将其添加到顶部

update: function(e, ui) {
updates[$(this).attr('id')]=true; //...

现在为在末尾激发的stop事件添加一个处理程序:

stop:function (e,ui) {
            if (updates.origin===true && updates.destination===true)
            {
             console.log('dragged from one group to another group');   
            }
            else if(updates.origin===true && updates.destination===false)
            {
             console.log('dragged within origin');   
            }
            else if(updates.origin===false && updates.destination===true)
            {
                console.log('dragged within destination');
            }
            //finally, clear out the updates object
            updates.origin=false;
            updates.destination=false;
        }

现在,控制台应该显示"在原点内拖动"或"在目标内拖动",如果某个对象在其自己的组内拖动。如果拖动到另一个组,它应该显示"从一个组拖到另一组"。

看小提琴:http://jsfiddle.net/Wr9d2/3/

PS如果你需要确定在组之间拖动时从哪个组开始和结束拖动,我认为代码很容易编辑。

我想到的另一种方法是计算拖动前后#origin列表的子元素数量并进行比较,而不是使用位置。如果它们不同,则调用的update函数来自#origin。您还需要比较元素ID以确保它们匹配。

首先在您的sortable声明之前添加以下内容:

var sender_id = null;
var sender_children = 0;

然后添加以下拖动启动选项:

    start: function(e, ui) {
        sender_id = $(this).attr("id");
        // Get number of child elements from the sender. We subtract 1
        // because of the placeholder (which adds another child)
        sender_children = $(this).children().length - 1;
    }

然后在update函数中,检查发送方的id是否匹配,ui.sender是否为null,发送方元素的子元素数是否不同。它应该少一个,因为您拖动的元素已被删除。如果是,那么跳过那个,因为它是从原点而不是目的地调用的。

    if ($(this).attr("id") == sender_id
        && ui.sender == null
        && $(this).children().length != sender_children
    ) {
        return true;
    }

请在JSFiddle上查看。