这是我的代码,来自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中。但是我无法拖动这些添加的元素。
如何使这些元素可拖动?
这是根据更新http://jsfiddle.net/XUFUQ/6/所需执行的操作的丑陋版本。最好将可继续使用的代码排除在外:
// let the trash be droppable, accepting the gallery items
$trash.droppable({
accept: "#list1 > li",
drop: function( event, ui ) {
$("#list2").append(ui.draggable);
addElements();
$( "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"
})
}
});
基本上,调用draggable仅连接到运行时存在的元素。这会将各种鼠标处理事件添加到每个元素。如果添加元素,它对它们一无所知,因此您需要在这些元素上再次调用draggable。
其他两个答案都给出了可以在何处添加可拖动对象以确保包含元素的示例,但这只是一个编码练习。
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다