2009-02-05 75 views
0

我正在研究利用jQuery UI可拖放/放置的概念證明。使用jQuery可拖放/放置在drop上設置變量

我正在尋找一種方法來設置一個變量,該變量等於放入放置區域的div的索引。 (說我有div的名爲「DIV0」,「DIV1」,「DIV2」,等...)

所以,想象一下代碼將是這個樣子:

<div id="div0" class="draggableDiv">some cotent</div> 
<div id="div1" class="draggableDiv">more content</div> 
<div id="div2" class="draggableDiv">yet more content</div> 

<div class="droppableDiv">drop it here</div> 

$(document).ready(function() { 
    $('.draggableDiv').draggable({helper: 'clone'}); 
    $('.droppableDiv').droppable({ 
     accept: '.draggableRecipe', 
     drop: function(ev, ui) { 
      ui.draggable.clone().fadeOut("fast", 
      function() { 
       $(this).fadeIn("fast") 
      }).appendTo($(this).empty()); 
         // function to set someVar = div[index]; 
     } 
    }); 
}); 

我不知道如何最好要做到這一點,所以如果有人有任何建議,我會很感激一些指導。

謝謝!

回答

0

您應該能夠通過使用

$.droppedItems = {}; 

var droppedId = $(this).attr('id').replace('droppable', ''); 
$.droppedItems[droppedId] = ui.draggable.attr('id').replace('div', ''); 
+0

啊,謝謝。所以現在想象我有多個div class =「droppableDiv」,所以說id =「drop0」,id =「drop1」,id =「drop2」。我怎麼能將可拖動div的currentIndex與可丟棄div的索引關聯起來?如果$(this)指的是可拖動的,我如何引用droppable? – jerome 2009-02-05 18:54:42

2
<div id="div0" class="draggableDiv">some cotent</div> 
<div id="div1" class="draggableDiv">more content</div> 
<div id="div2" class="draggableDiv">yet more content</div> 

<div id='dropplace' class="droppableDiv">drop it here</div> 

<script language='javascript'> 

$(document).ready(function() { 
    $('.draggableDiv').draggable({helper: 'clone'}); 
    $('.droppableDiv').droppable({ 
     accept: '.draggableDiv', //changed this, it was originally 'draggableRecipe' 
     drop: function(ev, ui) { 

       //get the index of dropped draggable div 
       var divIndex = $('div').index(ui.draggable) 
       alert(divIndex) //alert the divIndex to see the result 

       ui.draggable.clone().fadeOut("fast", 
       function() { 
         $(this).fadeIn("fast") 
       }).appendTo($(this).empty()); 
     } 
    }); 
}); 
</script> 

測試這樣一來解析div的ID,它爲我工作,希望會爲你工作了。好運

0

drop: function(ev, ui) {後添加:

var droppedId = ui.draggable.attr("id"); 

droppedId之後將是你div0div1,或div2之一 - 這取決於被放棄了。