如何动态添加列表元素在jquery中可拖动?

Sag*_*gar 4 jquery draggable jquery-ui-draggable

这是我的代码来自http://jsfiddle.net/XUFUQ/1/

$(document).ready(function()
    {
        addElements();
    }
);

function addElements()
{
    $("#list1").empty().append(
        "<li id='item1' class='list1Items'>Item 1</li>"+
        "<li id='item2' class='list1Items'>Item 2</li>"+
        "<li id='item3' class='list1Items'>Item 3</li>"
    );
}

$(function() {
    // there's the gallery and the trash
    var $gallery = $( "#list1" ),
    $trash = $( "#list2" );

    // let the gallery items be draggable
    $( "li", $gallery ).draggable({
        cancel: "button", // these elements won't initiate dragging
        revert: "invalid", // when not dropped, the item will revert back to its initial position
        containment: "document",
        helper: "clone",
        cursor: "move"
    });

    // let the trash be droppable, accepting the gallery items
    $trash.droppable({
        accept: "#list1 > li",
        drop: function( event, ui ) {
            $("#list2").append(ui.draggable);
            addElements();
    }
    });


});
Run Code Online (Sandbox Code Playgroud)

在文档就绪方法我将一些元素附加到list1,然后我在该列表上初始化draggable,所以我第一次能够拖动list1元素.在list2中删除我调用addElements()函数来清除并向list1添加一些元素.但我无法拖动这些添加的元素.

如何使这些元素可拖动?

ali*_*n45 16

这是我为任何未来寻求者做的一个小技巧:)这个代码只需运行一次,它几乎是不言自明的.

//The "on" event is assigned to the "document" element which is always available within the context
//Capture all the "mouseenter" event to any child element of "document" with a specific class (you can you any valid jQuery selector you like)
//any live and dynamic element with the class will become draggable (haven't tested on touchscreen devices)
$(document).on("mouseenter", '.someClass', function(e){
 var item = $(this); 
 //check if the item is already draggable
 if (!item.is('.ui-draggable')) {
         //make the item draggable
         item.draggable({
            .............
         });
  }
});
Run Code Online (Sandbox Code Playgroud)

干杯!