jquery:如何更新可拖动的克隆ID?

我想将可拖动项添加到可排序列表中,这在http://jsbin.com/ipese5/35上的示例中工作正常

问题是我想在拖动到可排序列表时更新克隆项的id。 奇怪的是,下面的代码在de ui对象中将id更新为“new-id”(我可以在我的控制台中看到),但是在实际的页面html上没有更改id。 有人有解决方案吗?

$( "#init .block" ).draggable({ helper: "clone", connectToSortable: ".list" }); $(".list").sortable({ connectWith: ".list", receive: function(event, ui) { $(ui.helper).attr("id","new-id"); console.log(ui); // surprisingly the next line works fine, but is not neccesary // $(ui.item).attr("id","new-id"); } }); 
Drag me
Drag me
Drag me
Sort me
Sort me

receive事件中,您无法访问在可排序列表中创建的实际项目。 帮助程序指向仅用于拖动的克隆,项目是您单击以拖动的原始项目。

但是, beforeStop事件在接收事件之前触发。 在beforeStop中,该项目实际上是要添加到列表中的项目。 因此,在beforeStop中,您可以保存该项目,然后在接收中使用它。

在这里演示: http : //jsfiddle.net/kcg29/

 var newItem; $(".list").sortable({ connectWith: ".list", beforeStop: function (event, ui) { newItem = ui.item; }, receive: function(event,ui) { $(newItem).doSomething(); } });​ 

这很简单,但有效:

 $( '#init .block' ).draggable({ connectToSortable: ".list", helper: "clone", start: function(event,ui){ //get ID form draggable item itemId = $(this).attr('id'); }, stop: function(event,ui){ //assign ID to clone ui.helper.attr('id',itemId); } }); $(".list").sortable({ connectWith: ".list", });