2016-05-05 38 views
2

我遇到了將jQueryUI droppable應用到動態創建的div的問題。jQuery UI可以動態添加元素嗎?

$(".item").draggable({ helper: 'clone'}); 

$(".box").draggable({containment : '#area'}); 
$(".box").droppable({ 
    drop: function(event, ui) { 
     if ($(ui.draggable).hasClass("area")){ 
      // call another function 
     }else{ 
      $(this).append($(ui.draggable).clone().removeClass('item').addClass('area')); 
      $('.area').draggable(); 
     } 
    } 
}); 

.item應該在.box下降。它工作得很好,直到我所說的第二個功能(通過點擊一個按鈕):

function add_box(){ 
    $("<div class='box'></div>").prependTo("#area"); 

    $(".box").droppable(); // i tried this (didn't work). 

    $(".box").draggable(); // should be draggable as well 
} 

回答

4

當你調用$(".box").droppable();add_box功能,你重新申請可棄所有.box的項目,但沒有選項,所以你失去了預期的行爲。

您應該只將它應用於新創建的元素,並且還需要定義您的選項。你可以做這樣的事情,例如:

// define your options as an object 
var droppableOptions = { 
    drop: function(event, ui) { 
     if ($(ui.draggable).hasClass("area")){ 
      // call another function 
     } else { 
      $(this).append($(ui.draggable).clone().removeClass('item').addClass('area')); 
      $('.area').draggable(); 
     } 
    } 
} 

function add_box(){ 
    var newBox = $("<div class='box'></div>").prependTo("#area"); 

    // you apply droppable to your new box, with the options you need 
    newBox.droppable(droppableOptions); 

    newBox.draggable(); // should be draggable as well 
} 
+0

我試過你的解決方案,但droppable/draggable不會應用到newBox。還有什麼我可以做的嗎?無論如何感謝 –

+0

我得到它使用$(newBox).droppable()。 –