jQuery Drag and Drop无法正常工作

时间:2012-04-24 13:48:25

标签: javascript jquery drag-and-drop

我正在尝试开发一个简单的拖放'游戏'。简单来说,您所做的就是将各种项目拖放到一个区域中,根据拖动的项目,它会说是正确还是错误。这是我到目前为止,它根本不工作,我不知道为什么。我对JS和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/

3 个答案:

答案 0 :(得分: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")
    ...

答案 1 :(得分: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! :(");
            }
        }
    });
});

答案 2 :(得分:0)

好吧,亚历克斯似乎把这个锁定了。

答案是:http://jsfiddle.net/aGqHh/1/

相关问题