【问题标题】:Enable draggable and droppable on dynamically created elements jQuery在动态创建的元素 jQuery 上启用可拖动和可放置
【发布时间】:2016-01-27 17:23:57
【问题描述】:

我想在动态创建的元素上自动启用“可拖动”和“可放置”。我不想在将元素添加到 DOM 后重新初始化它。

例如:

$('static_element_such_as_body').on('event', 'dynamicElement', function(){ 
    console.log('yayyyy'); 
});

这是一个真正的动态事件处理程序。如何将“可拖动”和“可拖放”添加到 .on 或 .live 活页夹?

有我用于拖放的代码:

    $('.draggable').draggable({
        helper: function() { //helper function is used to duplicate the event dragged


            return $('<p>winning</p>').append($(this).find('.name').clone()); //Idk what class or where .name is but without it, it bombs out
        },
        stack: ".draggable", //this changes our z index to be the upper most
        start: function(event, ui) { //this fires on start
            c.tr        = this; //set up our c cariable
            c.helper    = ui.helper;
        }
    }).droppable({ //this let's us know this element is droppable
        drop: function(event, ui) { //when you actually drop
            $(c.helper).remove();
        },
        over: function (event, ui) { //called when we are hovering over a droppable element with this selector
            console.log('over');
        },
        out: function(event, ui){
            console.log('left');
        }
    });

【问题讨论】:

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


    【解决方案1】:

    显然没有人知道,所以我想出了一个更“自动化”的解决方案。添加元素后,无需手动重新初始化它,您可以使用此事件处理程序为您自动重新初始化。

    $mainContainer.on('DOMNodeInserted', function(e){
        if($.inArray('relatable', e.target.classList) != -1){
            drag_drop_init();
            if(helper_bool_isRelatableEnabled){
                drag_drop_enable();
            }else{
                drag_drop_disable();
            }
        }
    });
    

    其中 $mainContainer 是一个静态元素,例如 $('body'),而 'relatable' 是我用来知道该元素应该允许拖放的类的名称。这是我用来初始化的类,即:$('.relatable').draggable()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 2013-11-20
      相关资源
      最近更新 更多