要更改新插入的项目,您应该使用 sortable 的接收事件。但是,截至今天,jQuery UI (1.8.11) 中有一个已知的限制/缺失功能,因此您无法轻松地从接收事件中访问克隆项目。现有的 ui.item 引用原始元素,而不是副本。
作为一种解决方法,您可以在拖动开始时向原始项目添加一个特殊类,您可以在接收事件上搜索可排序的项目(在克隆插入 DOM 后触发)。在拖动结束时,您必须确保无论发生什么,文档中的任何元素都不应设置特殊类。如果您正在复制/克隆,这一点尤其重要,因为 sortable 的接收事件会在可拖动对象的停止事件之前触发(我们从原始可拖动对象中删除特殊类)。
http://jsfiddle.net/3Gkrf/1/
HTML:
<ul>
<li id="test" class="dragme">Test</li>
</ul>
<ul class="sortme">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
CSS:
.dragme { border:1px solid silver; width:50px; height:50px; }
.newitem { background-color:yellow; }
javascript:
$(function(){
$(".sortme").sortable({
receive: function(){
$(this).find(".newitem").each(function(){
$(this).removeClass("newitem");
// Do your stuff with $(this), which is the newly created cloned item
});
}
});
$(".dragme").draggable({
connectToSortable: ".sortme",
helper: "clone",
start: function(){
$(this).addClass("newitem");
},
stop: function(){
$(this).removeClass("newitem");
}
});
});
如果您只想在拖动停止时手动创建另一个实例,则可以在可拖动对象的停止事件中实现。但是,我认为那里没有可靠的方法来检测它是放在可排序的还是其他地方。
stop: function(){
var clone = $(this).clone().appendTo("#wherever");
// do anything else with the clone variable here
}
您必须手动克隆您的对象,因为即使您设置了助手来克隆它,只要拖动停止,助手就会被销毁。如果它被放到一个 sortable 上,你可能会得到两个新对象,因为 sortable 在接收时会自动克隆。