jquery: how to update draggable clone id?

2019-02-10 08:32发布

问题:

I want to add draggable items to a sortable list, which works fine in my example on http://jsbin.com/ipese5/35

Problem is that I want to update id of the cloned item when dragged to the sortable list. Strange thing is that the following code updates the id to "new-id" in de ui object (as I can see in my console), but the id is not changed on the actual page html. Anyone has a solution?

$( "#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");
  }
});

<div id="init">
  <div id="new" class="block">Drag me</div>
  <div id="new" class="block">Drag me</div>
  <div id="new" class="block">Drag me</div>
</div>

<div class="list">
  <div class="block">Sort me</div>
  <div class="block">Sort me</div>
</div>

回答1:

In the receive event, you cannot access the actual item that is being created in the sortable list. Helper points to a clone that is used just for the dragging, item is the original item that you clicked on to drag.

But, the beforeStop event fires just before the receive event. In beforeStop, the item is actually the item being added to the list. So, in beforeStop you can save the item and then use it in receive.

Demo here: http://jsfiddle.net/kcg29/

var newItem;

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


回答2:

It's simple, but works:

$( '#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",
});