2011-04-06 85 views
41

如何獲取可丟棄元素的ID,何時丟棄物品?在這裏我使用jquery ui和asp.net mvc。jquery ui獲取可丟棄元素的ID,當丟棄物品

<table id="droppable"> 
    <tr> 
    <td style="width:300px;height:50px">Backlog</td> 
    <td style="width:300px;height:50px">Ready</td> 
    <td style="width:300px;height:50px">Working</td> 
    <td style="width:300px;height:50px">Complete</td> 
    <td style="width:300px;height:50px">Archive</td> 
    </tr> 
     <tr id="cart"> 
     <td id="BackLog" class="drag" style="width:120px;height:50px;"> 

     <img class="draggable" id="1234" src="../../Content/themes/base/images/ui-icons_222222_256x240.png" /> 

     </td> 
      <td id="Ready" class="drag" style="width:140px;height:50px"> 


      </td> 
      <td id="Working" class="drag" style="width:140px;height:50px"> 

      </td> 
      <td id="Complete" class="drag" style="width:140px;height:50px"> 


      </td> 
      <td id="Archive" class="drag" style="width:140px;height:50px"> 

      </td> 
     </tr> 
    } 
    </table> 

在這裏,我想將圖像移動到其他列,並獲得該列的ID。 拖放我使用腳本

<script type="text/javascript"> 
    $(function() { 
     $(".draggable").draggable({ containment: '#imageboundary', axis: "x" }); 
     $("#droppable").droppable({ 
      drop: function (event, ui) {          
       $.ajax({ 
        type: "POST", 
        url: '/Project/AddToPhase/' + $(ui.draggable).attr("id") , 
        success: function (data) { 
         $('.result').html(data); 
        } 
       }); 
      } 
     }); 
    }); 
</script> 

回答

2

你聯播一"drop"事件,並詢問您剛剛下降的元素。爲參數"ui"在以下的功能

$(".selector").droppable({ 
    drop: function(event, ui) { ... } 
}); 

元素有一個看看documentation.

+0

謝謝..我們需要更多解釋 – user685254 2011-04-06 09:07:28

95

要得到雙方的拖動和投擲的元素的ID,請使用下列內容:

$('.selector').droppable({ drop: Drop }); 

function Drop(event, ui) { 
    var draggableId = ui.draggable.attr("id"); 
    var droppableId = $(this).attr("id"); 
} 

對不起可能會有點晚,但我剛開始使用jQuery,需要確切的東西。

+0

有沒有更新? $(this).attr(「id」)似乎不再適用 – 2014-10-29 21:53:26

+1

對於我來說,'$(this)'仍然有效 – Lode 2015-01-09 10:51:06

+0

$(event.target).attr('id')適用於我,$ (this)did not – ccook 2015-04-09 19:53:09

5

的jQuery UI的droppable API manual提到如何獲得section of greedy option「下降 - 上可放開」非常「祕密」:

event.target可以檢查,看看哪些可放開收到 拖動元素

但是請注意,event.target只包含DOM元素...

回答您的問題

您將能夠通過第一個參數event獲取您的droppabledrop回調中的ID。

純JS

物業:event.target.id - 如果沒有設置ID:空字符串 「」
屬性:event.target.getAttribute('id') - 如果ID沒有被設置:空

jQuery的

屬性:$(event.target).prop('id') - 如果ID未設置:空字符串「」
屬性:$(event.target).attr('id') - 如果ID未被設置:未定義

用法例如

<script> 
$(function(){ 
    $(".droppablesSelector").droppable({ 
     drop: function (event, ui) {          
      //display the ID in the console log: 
      console.log(event.target.id); 
     } 
    }); 
}); 
</script> 

附加信息

Event
jQuery的事件系統歸根據所述事件對象 W3C標準。
傳遞給事件處理程序的事件對象保證爲 (不需要檢查window.event)。它 規範化目標,relatedTarget,其中,metaKey和pageX/Y 屬性並提供了stopPropagation()和preventDefault() 方法。