jquery ui get id of droppable element, when dropped an item

前端 未结 4 1863
刺人心
刺人心 2020-12-04 14:39

How we get the id of droppable element, when dropped an item? Here i use jquery ui and asp.net mvc.

 

        
                      
相关标签:
4条回答
  • 2020-12-04 14:53

    To get the id of both the draggable and the droppable elements use the following:

    $('.selector').droppable({ drop: Drop });
    
    function Drop(event, ui) {
      var draggableId = ui.draggable.attr("id");
      var droppableId = $(this).attr("id");
    }
    

    Sorry might be a little late for you but I have just started using jquery and needed the exact thing.

    0 讨论(0)
  • 2020-12-04 15:04

    jQuery UI's droppable API manual mentions how to get the "dropped-on-droppable" very "secretly" in the section of greedy option:

    event.target can be checked to see which droppable received the draggable element

    But note that event.target contains just a DOM element...

    Answer to your question

    You will be able to get the ID in your droppable's drop callback through the first parameter event.

    Pure JS

    Property: event.target.id - if ID is not set: empty string ""
    Attribute: event.target.getAttribute('id') - if ID is not set: null

    jQuery

    Property: $(event.target).prop('id') - if ID is not set: empty string ""
    Attribute: $(event.target).attr('id') - if ID is not set: undefined

    Usage example

    <script>
    $(function(){
        $(".droppablesSelector").droppable({
            drop: function (event, ui) {                                      
              //display the ID in the console log:
              console.log( event.target.id );
            }
        });
    });
    </script>
    

    Additional info

    Event
    jQuery's event system normalizes the event object according to W3C standards.
    The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods.

    0 讨论(0)
  • 2020-12-04 15:04
    <ul class="listitems">
        <li data-position="3">Item 3</li>
        <li data-position="2">Item 2</li>
        <li data-position="1">Item 1</li>
        <li data-position="4">Item 4</li>
    </ul>
    

    jQuery code

    $(".listitems li").sort(sort_li).appendTo('.listitems');
    // sort function callback
    function sort_li(a, b){
        return ($(b).data('position')) < ($(a).data('position')) ? 1 : -1;    
    }
    
    0 讨论(0)
  • 2020-12-04 15:05

    You hookup a "drop" event and interrogate the element that you just dropped. The element being the parameter "ui" in the function below

    $( ".selector" ).droppable({
       drop: function(event, ui) { ... }
    });
    

    Have a look at the documentation.

    0 讨论(0)
提交回复
热议问题