首页 > 解决方案 > 使用 Ajax 调用修改 DOM 后 JS 函数不起作用

问题描述

我有一个模式,其中内容由 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。

但是我尝试了很多不同的方法并阅读了很多但我无法让它工作......

标签: javascriptjqueryajax

解决方案


推荐阅读