【问题标题】:JQuery UI: Get ID of source element in drag'n'dopJQuery UI:在drag'n'dop中获取源元素的ID
【发布时间】:2012-12-07 09:21:20
【问题描述】:

我正在实施一个拖放操作,您可以在其中将用户拖放到某个角色。我知道如何获取用户 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>

提前感谢您的帮助。

【问题讨论】:

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


    【解决方案1】:

    勾上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 将其存储在元素上,然后在丢弃时检索它。

    【讨论】:

    • 谢谢你给了我我需要的提示......我刚刚在 droppable 的 drop 事件中做了ui.draggable.closest(".role").attr("id") ;)
    • @Hikaru-Shindo:啊,是的,当然。好东西!因为这与我的答案如此不同,所以您可能希望将其作为您自己的答案发布并(在两天后)接受它。这在 SO 上很好。当然,您的电话。无论如何,很高兴能帮上忙!
    • @T.J.Crowder,我可以请你看一下这里的 jQuery 可拖放相关问题:stackoverflow.com/questions/54498364/… 吗?
    【解决方案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');
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 2011-03-12
      • 2012-01-31
      • 1970-01-01
      • 2015-02-14
      • 2012-11-06
      • 2012-04-12
      • 1970-01-01
      相关资源
      最近更新 更多