New jQuery element added to DOM not working

I have a script that selects and drags multiple elements. It works fine, but when I want to add another element to this function, add it to the DOM, it will not work. Function:

$(function() {
        var selected = $([]), offset = {top:0, left:0};
        $("#selectable1").selectable();

        $("#selectable1 span").draggable({
            start: function(ev, ui) {
                $(this).is(".ui-selected") || $(".ui-selected").removeClass("ui-selected");

                $("span").removeClass("cica"); // ads class Cica to the draged/selected element
                $(this).addClass("cica");

                selected = $(".ui-selected").each(function() {
                    var el = $(this);
                    el.data("offset", el.offset());
                    $(this).text("Selected and dragging object(s)");
                });

                offset = $(this).offset();
            },
            drag: function(ev, ui) {
                var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
                selected.not(this).each(function() {

                    var el = $(this), off = el.data("offset");
                    el.css({top: off.top + dt, left: off.left + dl});

                });

            },
            stop: function(ev, ui){
                $(this).text("Drag has stopped");
            }
        });
    });

The new item is added as follows:

$('<span class="drag">Xia</span>').appendTo('#selectable1');

I know that I can use live to make it work, but I do not know where to add it to the script. I only know how to add it to an event, such as a mouse click, mouseover.

Please let me know if you have some tips on this.

thank

+3
source share
2 answers

, "# selectables1" , "dragSetup". :

$('#selectables1').bind('dragSetup', function() {
  $(this).find('span:not(.dragReady)')
    .draggable({ ... })
    .addClass('dragReady');
});

, , :

$('#selectables1').trigger('dragSetup');
+3

live DOM, DOM. jQuery Doc

+2

Source: https://habr.com/ru/post/1731451/


All Articles