【问题标题】:drag and drop on dynamically created div拖放动态创建的 div
【发布时间】:2012-05-11 10:31:56
【问题描述】:

我有一个拖放代码可以在服务器端创建的 div 上完美运行,但是当我使用 jquery(动态)创建一个 div 时,我似乎无法将任何东西放入容器中......

$('.dropcontent').droppable({
            accept: '.item',
            drop: function(ev, ui) {
               /* do something */
            }    
        });

        $(".item").draggable({  
           helper:'clone',
           appendTo: 'body',
           snap: true,
           revert: true

        });

    <div id="row1seo" class="dropcontent" > </div>   // original code on server side
    <div id="row1seo" class="dropcontent ui-droppable"> </div> // the above line becomes this on client side showing it has "binded" with the droppable
    <div id="row2seo" class="dropcontent"></div> // this the dynamically created div which doesn't seem to bind with the droppable. this is created in php file using ajax to retrieve it 

我也试过了

 $(".dropcontent").live('droppable', function() {
......
});

似乎不起作用...任何想法如何解决这个问题?

谢谢

【问题讨论】:

  • 动态创建的 div 是使用 ajax 从 php 文件中调用的...所以它不是使用 jquery/js 创建的
  • 只是设置一个小提琴,jsfiddle.net
  • 对于 js fiddle 来说太复杂了

标签: jquery jquery-ui drag-and-drop


【解决方案1】:

您必须启用拖动功能,以便它适用于生成的元素。太糟糕了 jQuery 的live() 函数不能处理拖放,所以你必须自己创建一个。我以这个函数为例:

(function ($) {
    $.fn.liveDraggable = function (opts) {
        this.live("mouseover", function() {
            if (!$(this).data("init")) {
                $(this).data("init", true).draggable(opts);
            }
        });
        return $();
    };
}(jQuery));

这样称呼它:

$( "element" ).liveDraggable()

您也可以轻松制作一个可放置的! GL!

【讨论】:

  • 不起作用 (function ($) { $.fn.liveDraggable = function (opts) { this.live("mouseover", function() { if (!$(this).data(" init")) { $(this).data("init", true).draggable(opts); } }); return $(); }; }(jQuery)); $('.dropcontent').liveDraggable({ 现在它甚至不会放入常规容器中
  • 这个功能适用于拖动,我自己经常使用它,您可以轻松地将其重写为可放置,只需替换单词..
  • 好人!祝你好运,随时回来 :D 并添加答案,以便其他人在查找时可以找到它!
  • (function ($) { $.fn.liveDroppable = function (opts) { this.live("mouseover", function() { if (!$(this).data("init" )) { $(this).data("init", true).droppable(opts); } }); return $(); }; }(jQuery)); $('.dropcontent').liveDroppable({
  • live 在 jquery 1.11.x 中被弃用
猜你喜欢
  • 1970-01-01
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-28
相关资源
最近更新 更多