使用Ajax Call进行DOM修改后,JS函数不起作用

时间:2018-11-16 19:44:11

标签: javascript jquery ajax

我有一个模态,其中通过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。

但是我尝试了很多不同的方式并阅读了很多东西,但是我无法正常工作...

0 个答案:

没有答案