【问题标题】:Get attribute ID of a Div element that's being dragged with JQUERY获取使用 JQUERY 拖动的 Div 元素的属性 ID
【发布时间】:2016-07-21 10:39:50
【问题描述】:

最近我一直在尝试获取正在拖动的 Div 的 id="whatever-id" 属性,但到目前为止我还没有成功。下面是我的代码(仅拖动部分),我尝试使用 ui 和事件对象获取此 ID 属性,但我看不出问题出在哪里。

$(function() 
{
    $( ".action-zone" ).draggable(
    { 
        scroll: true,
        helper:"clone",
        snap: ".actionDropAreaMovebleAction",
        snapMode: "inner",
        snapTolerance: 50,
        opacity: 0.7,
        forcePlaceholderSize: true,
        forceHelperSize: true,
        start: function( event, ui ) 
        {
            alert(ui.draggable.attr("id"));

            //INSERT THE DROP ZONE DIV IN ALL ELEMENTS EXCEPT ON THOSE WHOSE CLASS IS DRAGGINGACTION
            $( ".action-zone:not(.draggingAction)" ).after( "<div class='actionDropAreaMovebleAction'>\n\
                                            <div class='plus'>\n\
                                                <i class='fa fa-hand-o-down'></i>\n\
                                            </div>\n\
                                        </div>" );

            $(".actionDropAreaMovebleAction").addClass("highlighted");
            makeActionsDroppable();
        },
        stop:function( event, ui ) 
        {
            $(".actionDropAreaMovebleAction").removeClass("highlighted");
            $("div").remove(".actionDropAreaMovebleAction");
            $(this).removeClass("draggingAction");
            //alert("hallo");
        }
    });
});

如您所见,我尝试“alert()”类为“action-zone”的 DIV 元素的属性 ID仅用于测试目的,但是当警报出现时,我会返回一个“undefined”元素。

有人知道为什么会这样吗?

提前谢谢你。

【问题讨论】:

    标签: javascript jquery drag-and-drop attributes drag


    【解决方案1】:

    你只能使用ui.draggable来获取拖放到其他地方的可拖动对象,就像你可以在droppable中捕捉对象一样:

    $(".drop-zone").droppable({
      drop: function(event, ui) {
        console.log(ui.draggable); // will give you the draggable object
      }
    });
    

    但是,在您的 draggablestart 事件中,您可能会像这样获得对象的 id:

    $(".action-zone").draggable({
      start: function(event, ui) {
        console.log(ui.draggable); // will give you undefined
        console.log(event.target.id); // will give you the id
        console.log(event.target.attr('id')); // error!
        console.log($(event.target).attr('id')); // will give you the id
      }
    });
    

    【讨论】:

    • 你好 lozy219。我之前尝试在可拖动函数中输出“event.target.id”,但它也没有工作。我刚刚在 droppable 函数中应用了您的建议,但它并没有起作用。我仍然不确定。看:imageno.com/78qs52xowtnzpic.html
    • 如果没有更多细节,我无法判断拖放事件有什么问题。这是一个非常简单的演示,展示了如何通过event.target 获取 id。我使用了来自 jquery 站点的 html 示例。 jsbin.com/sisigurexu/edit?html,js,output
    • 你是对的。真的行。我的意思是,我创建了一个单独的文件并使用了您创建的这段代码并且它确实有效,但不知何故在我的主代码中它不起作用......我得看看我的整个代码,因为有些东西没有匹配..谢谢你的帮助 Lozy
    猜你喜欢
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2013-05-02
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多