简体   繁体   中英

Jquery Draggable and Droppable with Multiple Draggable

Kind of new to jquery and I am working with the draggable and droppable stuff. I have two draggables and a droppable. I can't quite figure out how to make it do different things based on which box I drop. Here is my jquery:

        $(function() {
            $( "#greatplan" ).draggable();
            $( "#droppable" ).droppable({
              drop: function( event, ui ) {
                $( this )
                  .addClass( "ui-state-highlight" )
                  .find( "p" )
                  .html( "Great Plan Picked!" )
              }
            });
             $( "#poorplan" ).draggable();
             $( "#droppable" ).droppable({
              drop: function( event, ui ) {
                $( this )
                  .addClass( "ui-state-highlight" )
                  .find( "p" )
                  .html( "Poor Plan Picked!" )

                }
          });

})

And my HTML:

         <div id="greatplan" class="ui-widget-content">
          <p>Great Plan!</p>
        </div>
        <br>
        <div id="poorplan" class="ui-widget-content">
          <p>Poor Plan!</p>
        </div>

        <div id="droppable" class="ui-widget-header">
          <p>Drop your plan here</p>
        </div>

No matter which box I drag into the droppable I always get "Poor Plan!". Any ideas?

You need one drop handler, with a test for which draggable element was dropped.

$(function() {
    $("#greatplan").draggable();
    $("#poorplan").draggable();

    $("#droppable").droppable({
        drop: function (event, ui) {
            switch (ui.draggable.attr('id')) {
                case "greatplan":
                    $(this).addClass("ui-state-highlight").find("p").html("Great Plan Picked!");
                    break;
                case "poorplan":
                    $(this).addClass("ui-state-highlight").find("p").html("Poor Plan Picked!")
                    break;
            }
        }
    });
});

DEMO

In your code you are overwritting the code that handles the drop event. It is going to always return poor plan because that is the most recent definition for it. You will have to differentiate between the ID of the object being dropped inside of the .droppable function.

How to get the dropped element's ID:

Get dropped elements id instead of drop target id

This would be easy with an if else statment, because you only have two elements to be dropped! If #greatplan is dropped, say "Great plan picked", else say "Poor plan picked". Hope that helps.

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