这是我来自 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/