jquery - $(document).ready() 内的范围? [英] jquery - scope inside $(document).ready()?

查看:12
本文介绍了jquery - $(document).ready() 内的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了保持井井有条,我有几个 javascript 文件,尽管它们(最终)都被缩小到一起形成一个最终的 javascript 文件.

So to stay organized, I have several javascript files, even though they all (in the end) are minified together to form one final javascript file.

每个文件的内容都包含在:

Each file's contents are wrapped in:

$(document).ready(function(){
    //some javascript here
});

似乎如果我在单独的文件中(在该代码之间)有东西,它们就无法相互访问.这是范围问题吗?我能做什么?

It seems like if I have things in separate files (in between that code) they don't have access to each other. Is this a scope issue? What can I do?

例如,在一个文件中,我有一堆代码来根据通过 ajax 接收的数据创建表.但是,文件的一半只是用于根据数据类型等显示数据的模板.我想将模板放在他们自己的文件中.

For example, in one file I had a bunch of code to create tables from data received through ajax. However, half of the file was just templates for how to display the data depending on it's types and such. I would like to have the templates in their own file.

我知道这只是一个偏好"问题,我可以将所有内容都放在一个文件中.

I understand this is just a 'preference' issue and that I could just have it all in one file.

但我希望能从中吸取教训,甚至可能以我的"方式行事.

But I'm hoping to learn from this and perhaps even be able to have it 'my' way.

推荐答案

Javascript 使用函数作用域,因此函数内部的局部变量对外不可见.这就是您的代码无法从其他范围访问代码的原因.

Javascript uses functional scopes, so local variables inside a function are not visible to the outside. This is why your code can't access code from other scopes.

对此的理想解决方案是创建一个命名空间.

The ideal solution to this is create a Namespace.

var NS = {};

(function(){
  function privateFunction() { ... }
  NS.publicFunction = function(){ ... }
})();

$(document).ready(function(){
  NS.publicFunction();
});

这也是一种有用的模式,因为它允许您区分私有和公共元素.

This is also a useful pattern because it allows you to make a distinction between private & public elements.

这篇关于jquery - $(document).ready() 内的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆