JQuery UI:获取drag'n'dop中源元素的ID

时间:2012-12-07 09:21:21

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

我无法阻止用户将用户拖到某个角色。我知道如何获取用户ID和目标角色ID,但我不知道如何获取用户被拖动的角色ID!

<div id="role_1" class="role">
    <h5>Administrator</h5>
    <ul class="users">
        <li id="user_1">Foo</li>
        <li id="user_2">Bar</li>
    </ul>
</div>
<div id="role_2" class="role">
    <h5>Member</h5>
    <ul class="users">
        <li id="user_1337">Baz</li>
    </ul>
</div>

<script type="text/javascript">
$(function() {
    // Get roles and users lists
    var $templates = $(".role"),
        $users = $(".users");

    // let the user items be draggable
    $("li", $users).draggable({
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: "document",
        helper: "clone",
        cursor: "move"
    });

    // let the roles be droppable, accepting the user items
    $templates.droppable({
        accept: ".users > li",
        activeClass: "ui-state-highlight",
        drop: function(event, ui) {
            var $uid = ui.draggable.attr("id"),
                $targetRid = $(this).attr("id"),
                $sourceRid = ???;
                // snip
        }
    });
});
</script>

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

挂钩start event,获取最接近的.role

$("li", $users).draggable({
    revert: "invalid", // when not dropped, the item will revert back to its initial position
    containment: "document",
    helper: "clone",
    cursor: "move",
    start: function() {
        var role = $(this).closest(".role").attr("id");
        // Here, role is either the id or undefined if no role could be found
    }
});

如果在删除时需要该信息,您可以使用start事件中的data将其存储在元素上,然后在删除时检索它。

答案 1 :(得分:2)

我认为你在开始拖动事件时需要记住这个id:

var srcId;
$("li", $users).draggable({
    revert: "invalid", // when not dropped, the item will revert back to its initial position
    containment: "document",
    helper: "clone",
    cursor: "move",
    start: function( event, ui ) {
        srcId = $(this).closest(".role").attr('id');
    }
});