【问题标题】:replaceWith and jQuery draggable drop?replaceWith 和 jQuery 可拖动拖放?
【发布时间】:2009-07-10 20:49:34
【问题描述】:

我试图理解为什么

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

将在外部工作

drop: function(event, ui) {}

jquery 的 droppable 脚本中的区域,但它不会在里面工作。具体来说,如果我这样做了

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

我收到了Runtime Error (line 1102) data(...).options is null or not an object。此外,如果我在 drop: 内插入 $('#title').append('ha');,它会起作用。 但是,如果我将$('#title').replaceWith('ha'); 放在外面的任何其他地方

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

有效吗?

【问题讨论】:

    标签: jquery jquery-ui jquery-plugins draggable droppable


    【解决方案1】:

    我将此作为答案发布,但实际上更多的是对 Jon Erickson 的答案的评论(我还没有声誉点可以发表评论)。 18 个月后,这仍然是 IE 中的一个错误,我只是想通过建议 setTimeout() 来详细说明“如何在 drop 函数之外运行某些东西”部分

    我通过将删除元素的匿名函数传递给 setTimeout() 来解决问题。根据您的快照或还原设置,您可能还需要考虑隐藏可拖动对象。

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

    【讨论】:

    • 感谢您,解决了我的问题!这只是 IE8 中的一个问题。在 IE9 中一切正常。
    • 谢谢!我讨厌必须支持 IE8,但可惜的是,我们的主要用户群都在使用它。
    【解决方案2】:

    id='title'的元素是否也有class='droppable'

    我可以查看它是否正在尝试删除会导致 drop 事件发生的元素,可能没有更多元素可以使用,并且您可能会收到“不是对象”错误。如果不亲自尝试,我不确定。

    也许你可以做的是用一些虚拟类标记对象(jQuery 的数据会更合适并符合 SRP,但这超出了这个答案的范围),然后在 droppable 的 drop 函数之外你可以更换

    类似...

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

    【讨论】:

    • 你是对的。 drop 事件是在没有更多元素可以删除的东西上触发的。 Firebug 帮助我确定了问题。
    最近更新 更多