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

标签 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();
    }
    });


});

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

如何使这些元素可拖动?

最佳答案

这是我为 future 的探索者做的一个小技巧:) 该代码只需运行一次,而且几乎是不言自明的。

//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({
            .............
         });
  }
});

干杯!

关于jquery - 如何在jquery中动态添加列表元素可拖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17941834/

相关文章:

javascript - jQuery Datepicker beforeShowDay 不工作

javascript - 在放置另一个可拖动元素时将可拖动元素交换为鼠标光标

javascript - 使所有 dom 元素可移动

JQueryUI - 可调整大小迫使我的 div 从位置 :Relative to Absolute 切换

javascript - 如何防止 JQuery 方法 .html() 改变大小写?

javascript - 如何使用iframe从我的网站查看pdf?

javascript - HTML 拖放持久化

draggable - 只限制一个方向的拖动

jquery - 将输入/复选框数据存储到 json 存储 - 按下按钮时

javascript - 从 jQuery 可拖动句柄中排除项目