2012-04-24 102 views
1

我想開發一個簡單的拖放'遊戲'。簡單地說,你所做的只是將各種物品拖放到一個區域,並根據拖動的項目說出正確或錯誤。這是我到目前爲止,它根本不工作,我不知道爲什麼。我對JS和jQuery的瞭解還有很多不足之處。jQuery拖放不工作

<script> 
$(function() { 
    $("#draggable").draggable(); 
    $("#wrong").draggable(); 

    $("#droppable").droppable({  
     drop: function(event, ui) { 
      var currentId = $(this).attr('id'); 
      if (currentId == "draggable") { 
       $(this) 
        .addClass("highlight") 
        .find("p") 
        .html("Correct! :)"); 
      } else { 
       $(this) 
        .find("p") 
        .html("Wrong! :("); 
      } 
     } 
    }); 
}); 
</script> 

現在我有工作,我需要拖動圖像的多個實例,但是當我添加更多的已經添加了新的不工作。

http://jsfiddle.net/KcruJ/9/

+0

你可以做你的代碼的的jsfiddle?或使用螢火蟲來檢查你是否有任何JavaScript錯誤。 – Kishore 2012-04-24 13:51:19

+0

在你的小提琴中:你不需要具有相同ID的元素。使用類而不是 – Valentin 2013-07-18 11:00:18

回答

0
var currentId = $(this).attr('id'); 
if (currentId == "draggable") 
    ... 

永遠不會導致如此,因爲$(this) represents the droppable the draggable is dropped on. ui.draggable represents the draggable[1]

嘗試:

var currentId = $(ui.draggable).attr('id'); 
if (currentId == "draggable") 
    ... 
0

這工作:http://jsfiddle.net/T6nu3/2/


$(this).attr('id'); 

將始終返回droppable。 您需要訪問拖動的元素:

$(ui.draggable).attr('id'); 

看看在jQuery UI Documentation以獲取更多信息。

代碼:

$(function() { 
    $("#draggable").draggable(); 
    $("#wrong").draggable(); 

    $("#droppable").droppable({ 
     drop: function(event, ui) { 
      var currentId = $(ui.draggable).attr('id'); 
      if (currentId == "draggable") { 
       $(this).addClass("highlight").find("p").html("Correct! :)"); 
      } else { 
       $(this).find("p").html("Wrong! :("); 
      } 
     } 
    }); 
}); 
+0

完美的感謝! :d – Jiggles 2012-04-24 14:11:36