【问题标题】:How to dynamically set up accepts for several Droppables如何为多个 Droppables 动态设置接受
【发布时间】:2014-08-27 07:54:45
【问题描述】:

我正在处理this demo。我正在研究如何只使用一次调用.droppable() 和接受选项,以便通过拖放特定 ID 来接受可拖动元素。所以:

dropboxt0 接受 dragboxt0
dropboxt1 接受 dragboxt1
dropboxt2 接受 dragboxt2
dropboxt3 接受 dragboxt3
dropboxt4 接受 dragboxt4

我使用了以下代码

$(".dragbox").draggable();
$(".dropbox").droppable({
    accept:   $(this).attr('id'),
    drop: function (event, ui) {
        $(this)
            .addClass("ui-state-highlight")
            .html("Dropped!");
    }
});

但它没有做这项工作。

【问题讨论】:

    标签: jquery jquery-ui jquery-ui-draggable jquery-ui-droppable


    【解决方案1】:

    这个问题已经在这里讨论过了:jquery droppable accept

    您可以使用一个必须返回 true 或 false 的函数,而不是使用单个选择器来接受。 在函数内部,有很多方法可以达到您想要的行为。我选择以下:

    <div id="container">
        <div class="dropbox" data-drop-id="db01"></div>
        <div class="dropbox" data-drop-id="db02"></div>
        <div class="dropbox" data-drop-id="db03"></div>
        <div class="dropbox" data-drop-id="db04"></div>
        <div class="dragbox" data-drag-id="db01"></div>
        <div class="dragbox" data-drag-id="db02"></div>
        <div class="dragbox" data-drag-id="db03"></div>
        <div class="dragbox" data-drag-id="db04"></div>
    </div>
    

    js 带accept - 函数,返回真假:

    $(".dropbox").droppable({
    accept: function (myDragBox) {
        var id_group_drop, id_group_drag;
        //get the "id_group" stored in a data-attribute of the draggable
        id_group_drag = $(myDragBox).attr("data-drag-id");
        //get the "id_group" stored in a data-attribute of the droppable
        id_group_drop = $(this).attr("data-drop-id");
        //compare the id_groups, return true if they match or false otherwise
        return id_group_drop == id_group_drag;
    },
    drop: function (event, ui) {
        $(this)
            .addClass("ui-state-highlight")
            .html("Dropped!");
    }
    

    });

    我比较重要的是,drop 和 dragbox 的 id 是相同的。因此我没有使用 id 属性,而是我自己的 data-id 属性,因为我喜欢让我的 id 是唯一的......

    在此处查看演示:http://jsfiddle.net/u9w63y2q/1/

    【讨论】:

    • 谢谢,这正是我要找的东西
    • 不要忘记关注我帖子中的 stackoverflow 链接,并尊重 alex 和 morten 的解决方案,因为我所做的只是进入 jquery api 文档 - 看到,“接受”也接受一个函数并在stackoverflow中搜索了这个函数;)
    猜你喜欢
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2017-10-07
    • 2013-10-23
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    相关资源
    最近更新 更多