jquery .load with script in it

时光总嘲笑我的痴心妄想 提交于 2021-02-05 11:46:37

问题


I need load piece of content into my div, I need execute the script I have in remote div, for example I have

<div id="thisIsRemoteContent">
<script src="blabla.js"></script>
</div>

in the remote-content.html

Now I need load it with script to my page

$('.mydiv').load("remote-content.html #thisIsRemoteContent");

In jquery API documentation was written that if I load piece of contet, then the script will not be executed.

When calling .load() using a URL without a suffixed selector expression, the content is passed to .html() prior to scripts being removed. This executes the script blocks before they are discarded. If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

However, how can I load it with script?


回答1:


cant you do 2 calls?

    $('.mydiv').load("remote-content.html");
    $.getScript('blabla.js');

you can manipulate with the script name so the remote content will know what its name and then put it in some attribute inside the remote-content.html like:

<div>my remote content</div>
<span scriptname="blabla.js"></span>

so then:

    $('.mydiv').load("remote-content.html");
    $.getScript($('span[scriptname]').attr('scriptname'));


来源:https://stackoverflow.com/questions/21723154/jquery-load-with-script-in-it

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