replaceWith and jQuery draggable drop?

2019-07-25 00:20发布

I'm trying to understand why

$('#title').replaceWith('ha'); 

will work outside the

drop: function(event, ui) {}

area in jquery's droppable script, but it won't work inside. Specifically, if I do

$(".droppable").droppable({
drop: function(event, ui) {
    $('#title').replaceWith('ha'); 
     }

I get a Runtime Error (line 1102) data(...).options is null or not an object. Also if I insert a $('#title').append('ha'); inside the drop:, it works. However if I put $('#title').replaceWith('ha'); anywhere else outside

$(".droppable").droppable({ /* */  });

it works?

2条回答
看我几分像从前
2楼-- · 2019-07-25 00:30

I'm posting this as an answer but really its more of a comment on Jon Erickson's answer (I don't have the reputation points to comment yet). 18 months later this is still a bug in IE and I just wanted to elaborate on the 'how to run something outside of the drop function' part by suggesting setTimeout()

I am solving the problem by passing an anonymous function that removes the element to setTimeout(). Depending on your snap or reversion settings you might want to also consider hiding the draggable.

$(".droppable").droppable({
    drop: function(event, ui) {
        // do something interesting here...

        // now get rid of the draggable
        $(ui.draggable).hide();           
        setTimeout(function(){$(ui.draggable).remove();}, 1);
    }
});
查看更多
对你真心纯属浪费
3楼-- · 2019-07-25 00:37

Does the element with id='title' also have class='droppable'

I could see if it is trying to remove an element that would cause the drop event to occur there may be no more element to work with and you could get a 'not an object' error. I don't know for sure without trying this out myself.

Maybe what you can do is mark the object with some dummy class (jQuery's data would be more suitable and comply with the SRP, but that is out of the scope of this answer), and then outside of the droppable's drop function you can do the replacement

something like...

$(".droppable").droppable({
    drop: function(event, ui) {
        // mark the element for replacement
        $('#title').addClass('replaceThisElement'); 
    }
});

// outside of the drop function
$('#title .removeThisElement').replaceWith('ha');
查看更多
登录 后发表回答