2016-07-21 31 views
0

最近我一直在試圖獲得ID =正在被拖動的Div的「whatever-id」屬性,但到目前爲止我還沒有成功。下面你會發現我的代碼(只有拖動部分),我試圖用ui和事件對象來獲取這個ID屬性,但是我看不出問題在哪裏。獲取被JQUERY拖動的Div元素的屬性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"); 
     } 
    }); 
}); 

正如你可以看到我嘗試「警報()」帶班「行動區」只是爲了測試的目的,但是當DIV元素的屬性ID警報來了,我得到一個「undefined」元素。

沒有人有任何想法,爲什麼這所發生的情況?

我提前感謝你。

回答

0

您只能使用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 
    } 
}); 
+0

你好lozy219。我試圖在可拖動函數內輸出「event.target.id」,但它沒有任何效果。我剛剛將這些建議應用到了droppable函數中,並且它不起作用。我仍然沒有定義。看:http://www.imageno.com/78qs52xowtnzpic.html –

+0

沒有更多的細節,我不能告訴拖放事件有什麼問題。這是一個非常簡單的演示,展示瞭如何通過'event.target'獲取id。我使用jQuery網站的html例子。 https://jsbin.com/sisigurexu/edit?html,js,output – lozy219

+0

你說得對。真的行。我的意思是,我創建了一個分離的文件,並使用了你創建的代碼,它確實起作用了,但是在我的主代碼中它不工作......我得看看我的整個代碼,因爲「某些東西不比賽..謝謝你的幫助Lozy –