简体   繁体   中英

jQuery Drag and Drop not working

I am trying to develop a simple drag and drop 'game'. In simple terms all you do is drag and drop various items into a area and it will say correct or wrong depending on the item dragged. This is what I have so far and its not working at all and I dont know why. My knowledge of JS and jQuery leaves a lot to be desired too.

<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>

Now that I have it working I need more instances of the draggable images but when I add more the the new ones that have been added don't work.

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

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

Will never result true, as $(this) represents the droppable the draggable is dropped on. ui.draggable represents the draggable $(this) represents the droppable the draggable is dropped on. ui.draggable represents the draggable [1]

Try:

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

This works: http://jsfiddle.net/T6nu3/2/


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

Will always return droppable . You need to access the dragged element:

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

Take a look at the jQuery UI Documentation for more information.

Code:

$(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! :(");
            }
        }
    });
});

haha well, Alex seems to have this one on lock.

There's the answer: http://jsfiddle.net/aGqHh/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM