Triggering a drop event with jQuery droppables

荒凉一梦 提交于 2019-12-23 11:44:13

问题


Variations of this question have been asked, but the answers are all different, somewhat dated, and aren't working for me so I'm hoping it's a matter of changed syntax rules in jQuery that I'm missing.

The scenario HTML:

<div id="theDroppable">Droppable</div>
<div id="theDraggable">Draggable</div>
<div id="theTrigger">Click to trigger a drop</div>

The jQuery:

$( "#theDroppable" )
    .droppable({
      drop: function( event, ui ) {
          alert('dropped');
      }
    });

$( "#theDraggable" ).draggable({});

$( "#theTrigger" ).click(function(){$( "#theDroppable" ).trigger('drop')});

The fiddle: http://jsfiddle.net/7Bewj/

The above creates a Droppable, a Draggable, and a div that I'd like to use to somehow trigger the function associated with the drop event on the droppable.

The draggable works fine, dragging it to the droppable and releasing triggers the alert.

The question is how can I trigger that same process without using an actual draggable...or at least without using a draggable that is dropped on top (such as by clicking the 3rd div)?


回答1:


As you can see from the function:

drop: function( event, ui ) {
      alert('dropped');
  }

If you define methods such as DROP during the declaration of droppable then they are called only when a DOM element(UI object) is dropped on them hence you can't trigger those function.

If you need to trigger DROP then I would suggest you to bind that event to the droppable as:

$( "#theDroppable" ).droppable({hoverClass : 'droppableStyle'});
$( "#theDroppable" ).on('drop',function(event,ui){
    alert('dropped');
});

The DROP function can now be triggered by dropping 2nd DIV or by clicking 3rd DIV as in your case. Trigger it manually using:

 $( "#theDroppable" ).trigger('drop');

NOTE: The argument 'ui' will be undefined if triggered manually, else it will contain the UI object when draggable is dropped on it.

Here is jsFiddle



来源:https://stackoverflow.com/questions/21273181/triggering-a-drop-event-with-jquery-droppables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!