Why is javascript code not loaded when injectet into Bootstrap 4 Modal?

冷暖自知 提交于 2019-12-08 13:27:28

i think I found a solution. This is more a problem of jQuery and not Bootstrap. jQuery is simply not executing the content of <script>-Tags anymore. I added this to the bottom of my showModal(...) function right before the return statement:

...
if(message){
    var reponseScript = $(message).filter("script");
    $.each(reponseScript, function(idx, val) { 
        eval(val.text);
    } );
}
$(body).trigger('load');
...

What does it do: It filters the javascript from the server-response. After that it's executed with eval.

The $(body).trigger('load'); executes the code within the injected ready()-function. I still have to test it a little more. I'm afraid, that other ready() methods are also called again.

Here my full showModal Function:

therapy.showModal = function(message, headerMessage, sticky, noFooter){
        var modal = $('<div />',{
                class: 'modal fade hide',
                role: "dialog",
                'aria-labelledby': "modalTitle",
                'aria-hidden': "true",
                tabindex: -1
        });

        var modalDialog = $('<div />',{
                class: 'modal-dialog',
                role: "document"
        });
        modal.append(modalDialog);

        var modalContent = $('<div />',{
                class: 'modal-content'
        });
        modalDialog.append(modalContent);



        var header = $('<div />',{
                class: 'modal-header'
        });
        if(headerMessage == undefined) headerMessage = "&nbsp;";
        header.html("<h3 id='modalTitle'>"+headerMessage+'</h3> <button type="button" class="close" data-dismiss="modal" aria-label="Schließen"><span aria-hidden="true">&times;</span></button>');
        modalContent.append(header);


        var body = $('<div />',{
                class: 'modal-body'
        });
        body.html(message);
        modalContent.append(body);

        if(noFooter != true){
                var footer = $('<div />', {
                        class: 'modal-footer'
                });
                footer.html('<button type="button" class="btn btn-primary" data-dismiss="modal" aria-hidden="true">OK</button>');
                modalContent.append(footer);
        }
        var options = {};
        options.show = true;

        if(sticky == true){
                options.backdrop="static";
        }

        modal.modal(options);
        //$(modal).trigger('load');

        // Get javascript if any and execute...
        // see: https://stackoverflow.com/a/7330106/1219104
        if(message){
                var reponseScript = $(message).filter("script");
                $.each(reponseScript, function(idx, val) { 
                        eval(val.text);
                } );
        }
        $(body).trigger('load');
        return modal;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!