简体   繁体   English

在使用 jquery .load() 加载的 html 范围内未定义全局函数

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

I have html with :我有 html :

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

in app.js I have function foo:在 app.js 我有函数 foo:

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

Then I have jquery and use it's method .load to load external html content:然后我有 jquery 并使用它的方法 .load 加载外部 html 内容:

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

Output of /modal_dialog_ajax looks like: /modal_dialog_ajax输出如下所示:

<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. Javascript 执行得很好,但在此 html 的范围内未定义foo()调用。

Why Js inside ajax loaded html content does not see global functions defined on the page?为什么Js里面的ajax加载的html内容看不到页面上定义的全局函数?

Workarounded this using window global object:使用 window 全局对象解决了这个问题:

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

And then call it as然后将其称为

window.foo();

But not sure it is a good practice.但不确定这是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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