简体   繁体   中英

How to execute a function when an element is drag and dropped

I have a sorta-basic jquery/javascript question.

The code below will create objects which can be dragged and dropped. If you click on an object, it will display the ID of the "next" object.

I wish to return this value (of the next object's ID) when the object is first "grabbed" (picked up without deliberately clicking) and then return the ID of the "next" object where it is placed.

Ideally, if the ID of the location it is grabbed is equal to the location where it is placed, it should not return any ID.

The Jquery & Javascript

$(function() {
    $( "#sortable" ).sortable();
    $( "#sortable" ).disableSelection();
});

$("li").live("click",function(e) {
    document.getElementById("result").innerHTML=($(this).next("li").attr('id'))
});

The CSS:

#sortable { list-style-type: none; margin: 0; padding: 0; }
#sortable li { margin: 3px 3px 3px 0; padding: 1px; float: left; width: 100px; height: 90px; font-size: 4em; text-align: center; }
</style>

The HTML:

<div class="container">

<ul id="sortable">
    <li id="li1" class="ui-state-default">1</li>
    <li id="li2" class="ui-state-default">2</li>
    <li id="li3" class="ui-state-default">3</li>
    <li id="li4" class="ui-state-default">4</li>
    <li id="li5" class="ui-state-default">5</li>
    <li id="li6" class="ui-state-default">6</li>
</ul>

</div>

<br><div id="result">Result Placed Here</div>

I don't even know where to start because I do not know how to run the function without it being clicked (without grabbing).

Any help is greatly appreciated,

Taylor

A JSfiddle can be found here: http://jsfiddle.net/TSM_mac/uuHsg/4/

Use the sortable events start and stop .

$(function() {
    function startCallback(event, ui) {
        // stuff
    }

    function stopCallback(event, ui) {
        // other stuff
    }

    $("#sortable").sortable({
        start: startCallback,
        stop: stopCallback
    }).disableSelection();
});

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