简体   繁体   中英

Global function is undefinded in scope of html loaded using jquery .load()

I have html with :

<script src="/js/app.js"></script>

in app.js I have function foo:

function foo() { console.log("foo") }

Then I have jquery and use it's method .load to load external html content:

$("#modal-wrapper").load("/modal_dialog_ajax", function () {
   // Some logic
});

Output of /modal_dialog_ajax looks like:

<div>Some markup</div>
<script type="text/javascript">
 foo();
</script>

Javascript is executed fine but call of foo() is undefined in the scope of this html.

Why Js inside ajax loaded html content does not see global functions defined on the page?

Workarounded this using window global object:

function foo() { console.log("foo") }
window.foo = foo;

And then call it as

window.foo();

But not sure it is a good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM