Функции JS не работают после модификации DOM с помощью Ajax Call - PullRequest
0 голосов
/ 16 ноября 2018

У меня есть модал, где контент загружается с помощью вызова Ajax.

Вызов Ajax загружает новую форму в модальное тело, и мне нужно использовать некоторые js-плагины в этой форме (отобразить карту, использовать TinyMCE, Chosen.js и т. Д.)

Я перепробовал много вещей, которые читал в других постах, но ни одна из них не работает для меня ...

// Performs a lot of things
function init() {
    $('.chosen').chosen();
    $('.toggleswitch').bootstrapToggle();
    tinymce.init();
}

// Long Google Maps function
function initAutocomplete() {
    // a lot of code
}

// Another Google Maps function
function fillInAddress() {
    // a lot of code
}

//The problematic function
$('#modalEditLieu').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget);
    var lieu_id = button.data('lieu-id');
    $("#modalEditLieu .modal-body").html('').addClass('loading');
    $.get( "/lieux/" + lieu_id + "/edit", function( data ) {
        // Here I fill modal body with html send by ajax call
        $("#modalEditLieu .modal-body").html(data).removeClass('loading');

        // I tried to call functions again here
        init();
        initAutocomplete;
        fillInAddress();

        // I also tried to put it in 
        // $("#modalEditLieu .modal-body").html(data).promise().then(...) 
        // as suggested in some posts

    });
});

// I call all the functions in here
$('document').ready(function () {
    init();
    initAutocomplete;
    fillInAddress();
});

// I tried to call it in the ajaxComplete event as suggested but it does not work
$( 'document' ).ajaxComplete(function() {
    init();
    initAutocomplete;
    fillInAddress();
});

Я понимаю, что функции, вызываемые при первой загрузке, основаны на первом DOM и что они не будут работать с динамически загружаемым html.

Но я пробовал много разных способов и много читал, но я не могу заставить его работать ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...