简体   繁体   中英

jquery draggable droppable remove dropped

How would one remove the item from the shopping cart?

Naturally you would want to be able to drag and drop the item back.

$(function() {
        $( "#catalog" ).accordion();
        $( "#catalog li" ).draggable({
            appendTo: "body",
            helper: "clone"
        });
        $( "#cart ol" ).droppable({
            activeClass: "ui-state-default",
            hoverClass: "ui-state-hover",
            accept: ":not(.ui-sortable-helper)",
            drop: function( event, ui ) {
                $( this ).find( ".placeholder" ).remove();
                $( "
  • " ).text( ui.draggable.text() ).appendTo( this ); } }).sortable({ items: "li:not(.placeholder)", sort: function() { // gets added unintentionally by droppable interacting with sortable // using connectWithSortable fixes this, but doesn't allow you to customize active/hoverClass options $( this ).removeClass( "ui-state-default" ); } }); });

    This should work:

    $(function() {
        $("#catalog").accordion();
        $("#catalog li").draggable({
            appendTo: "body",
            helper: "clone"
        });
        $("#cart ol").droppable({
            activeClass: "ui-state-default",
            hoverClass: "ui-state-hover",
            accept: ":not(.ui-sortable-helper)",
            drop: function(event, ui) {
                $(this).find(".placeholder").remove();
                $("<li></li>").text(ui.draggable.text())
                    .addClass("cart-item")
                    .appendTo(this);
            }
        }).sortable({
            items: "li:not(.placeholder)",
            sort: function() {
                $(this).removeClass("ui-state-default");
            }
        });
        $("#catalog ul").droppable({
            drop: function(event, ui) {
                $(ui.draggable).remove();
            },
            hoverClass: "ui-state-hover",
            accept: '.cart-item'
        });
    });
    

    Notes :

    • When an item is dropped on the cart area, I've added a class of cart-item to the new item.
    • I've made the catalog's ul droppable; this area only accepts cart-item s. It calls remove() to remove an item from the cart once the drop has occurred.

    See it working here: http://jsfiddle.net/andrewwhitaker/t97FE/embedded/result/

    You can drag an item back from the cart to any category in the catalog, but I think it would be pretty easy to make items only draggable to their original categories.

    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