【问题标题】:How to auto apply drag and drop effect to dynamically added element?如何自动将拖放效果应用于动态添加的元素?
【发布时间】:2011-02-04 17:56:51
【问题描述】:

我使用jquery ui对一系列DIV应用拖放效果,例如:

<div class="draggable">...</div>
<div class="draggable">...</div>
<div class="draggable">...</div>
<div class="draggable"> this DIV was dynamically added, not draggable </div>

问题是动态添加的 DIV 不会应用此效果,我如何将这种效果也应用到新成员上?

【问题讨论】:

    标签: php jquery jquery-ui


    【解决方案1】:

    您不能直接将 .live() 函数与 .draggable() 一起使用,但您可以将 .live() 与 mouseover 事件一起使用,并像这样在 mouseover 上重新附加 .draggable()。

    $('.draggable').live('mouseover',function(){
        $(this).draggable();
    });
    

    【讨论】:

    • 稍微看一下,也许在使其可拖动之前检查该项目是否已经可拖动会更好。 $('.draggable').live('mouseover',function(){ if(!$(this).hasClass('ui-draggable')) { $(this).draggable(); } });
    • .live 现在已被弃用。最好使用 .on:- $(body).on('mouseover', '.draggable', function(){ $(this).draggable(); })
    【解决方案2】:

    看看 jQuery .live()。我相信你可以在这里使用它。如果不是 - 只需在创建元素时附加 .draggable()

    【讨论】:

      【解决方案3】:

      您可能还想在 jQuery 1.4 中引入的 delegate() 方法中掠夺一下,它比 live() 稍微好一点

      这是一篇比较两种方法的文章 - http://net.tutsplus.com/tutorials/javascript-ajax/quick-tip-the-difference-between-live-and-delegate/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-20
        • 1970-01-01
        • 1970-01-01
        • 2016-07-16
        • 1970-01-01
        相关资源
        最近更新 更多