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

匿名 (未验证) 提交于 2019-12-03 09:13:36

问题:

I have a javascript function which opens a Bootstrap Modal Dialog:

In the next step I'm loading a HTML snippet from the server, which I want to pass into the showModal() Function as message. Here is an example snippet loaded from server via ajax and stored in the JS-Variable mySnip

<p>Foo text</p> <script type="text/javascript" >    alert("Alert1");    $(document).ready(function(){       alert("Alert2");    }); </script> 

After that I open the Modal-Dialog with the loaded with the snippet as parameter:

showModal(mySnip, "Header", true, false); 

My problem is, that the Javascript part of the snippet is not loaded. Does anybody know how I can get the Javascript of the snippet executed? (So that the Alerts are shown)

Background:

I'm migrating from Bootstrap 2 to Bootstrap 4. This method worked perfectly fine in Bootstrap 2. I know that this can be achieved in an other way, but I'm migrating a big application with dozens of Modals which are working in this way.

回答1:

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:



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!