gpt4 book ai didi

javascript - 外部文件中的 Document.ready?

转载 作者:可可西里 更新时间:2023-11-01 01:47:17 24 4
gpt4 key购买 nike

我在 HTML 页面上引用 JavaScript 如下:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0b1/jquery.mobile-1.0b1.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&amp;region=GB"></script>
<script type="text/javascript" src="js/shared.js"></script>
<script type="text/javascript">
$('document').ready(function() {
// In-page code: call some functions in shared.js
});
</script>

shared.js 中定义的函数没有包含在 $('document').ready 中。所以:

  1. 假设 shared.js 中定义的函数可用于“页内代码”是否安全?

  2. 如果我将页内代码提取到一个名为 local.js 的单独文件中(将其包装在 $('document').ready 中),是否仍然可以安全地假设 shared.js 中定义的函数可用?

  3. 最后,我没有将 shared.js 包装在 $('document').ready 中是否有问题?我发现如果我确实包装它,它的功能将不再可用于页内代码。

问题 3 的原因是我遇到了这个问题:Uncaught TypeError: Property ... is not a function - after page has loaded

并想知道这是否与我组织代码的方式有关。

更新:感谢您的回答。现在很清楚,在 shared.js 中使用 $('document').ready 会从全局范围中删除这些函数。但是,我只想澄清第 3 点中的原始问题。

我可以假设如果我执行以下操作:

  • 在我的页内代码中,加载到 $('document').ready 中,从 shared.js 调用一个函数
  • 让 shared.js 中的函数引用 jQuery、Google map 或我页面上的元素

不会有问题吗?

换句话说,是否可以安全地假设页面将在 shared.js 中的函数被调用时加载,即使我没有将该文件中的所有内容都包装在 $('document').ready?

最佳答案

Is it safe to assume that functions defined in shared.js are available to the "in-page code"?

是的,只要那些函数被注入(inject)到全局范围内

If I pull out the in-page code into a separate file called local.js (keeping it wrapped in $('document').ready), is it still safe to assume that functions defined in shared.js are available?

是的,只要在 shared.js 之后包含 local.js AND shared.js 将函数注入(inject)全局范围。

Finally, is the fact that I'm not wrapping shared.js inside $('document').ready a problem? I'm finding that if I do wrap it, its functions are no longer available to the in-page code.

document.ready 中的包装函数将它们带出全局范围。

var foo = 4; // global
$(function() {
var bar = 5; // local
});
foo = bar; // error

你需要在全局范围内注入(inject)变量,这很简单

$(function() {
/* all your code */

window["SomeGlobalVariable"] = someFunctionIWantGlobal;
});

关于javascript - 外部文件中的 Document.ready?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6547883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com