开发者

jQuery - manipulate dropped element in sortable list

I have a dra开发者_如何学Cggable list (.field) where you can drag & drop items from it into a sortable list (.sortlist). I did it this way because I didn't want the master list (.field) altered in any way. It works fine, except I cannot work out how to manipulate the dropped field in a sortable list.

I can do it from a draggable into a droppable area by using the following in a function for 'drop:' in droppable():

$(this).append('html code here to change content of dragged field');

However this doesn't work inside a sortable(). My code looks like this:

$(".sortlist").sortable({
  receive: function(event, ui) {
    var dropElemTxt = $(ui.item).text();
    var dropElemId = $(ui.item).attr('id');
    $(ui.item).replaceWith('<li class="box" id="'+dropElemId+'">Updated field! '+dropElemTxt+'</li>');
  }
});

$(ui.item).replaceWith changes the master field that was being dragged, so this doesn't work. And I tried $(this).replaceWith, but that updates the sortable area (.sortlist).

Any idea what code I need to reference the dragged item?

Many thanks, Ali.


You could get the dragged item in beforeStop event:

beforeStop: function (event, ui) { draggedItem = ui.item;},
receive: function (event, ui) { /* use draggedItem here*/ }

Using beforeStop event instead of receive was enough for me:

beforeStop: function(event, ui) { 
        var myClassItem = $('.myClass', ui.item);
        myClassItem.bind('click', function(){ /*my function*/ });
    }


I think I've worked it out. A bit hacky, but seems to work!

I need to use $('.sortlist li:last') to access the dragged element...


I followed your line of thinking, but there were a few bugs using this approach (sometimes the element being dropped just disappeared when using droppable + sortable). Here's something that worked out for me:

$(".draglist").draggable({
  start: function(e, ui) {
    draggedItem = ui.item;
  }
});

$(".sortlist").sortable({
  receive: function(event, ui) {
    //do something with the 'draggedItem' here...
    var droppedElemTxt = draggedItem.text();
    var droppedElemId = draggedItem.attr('id');
  }
  , start: function(e, ui) {
    draggedItem = ui.item;
  }
});


Not being able to access the dropped element is a known bug in JQuery ui sortables. The ticket contains a patch that allows you to access the dropped element, and this is expected to be fixed in the next major release.


I think I actually came up with a better solution... seems to work so far...

I attached a droppable to a sortable to declare a global var of the dragged item. A bit like so:

$(".sortlist").droppable({
  drop: function(e, ui) {
    draggedItem = ui.draggable;
  }
}).sortable({
  receive: function(event, ui) {
    //do something with the 'draggedItem' here...
    var droppedElemTxt = draggedItem.text();
    var droppedElemId = draggedItem.attr('id');
  }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜