我正在使用 jquery,并且对我编写代码的方式感到非常沮丧。几个月前,我开始使用 JS 和 Jquery 进行编码,我的代码如下所示:
$(document).ready(function(){
$(function(){// a function that applies a plugin to an element});
$(function(){// another function that applies a plugin to an element});
$(function(){// and another function that applies a plugin to an element});
$(function(){// yet another function that applies a plugin to an element});
});
$(function(){//functions applied to certain elements that does not require to be initially loaded})
基本上我之前所做的就是将所有内容放入 $(document).ready
这就是我现在的编码方式
function a(){//a function that applies plugin to an element}
function b() {// another function}
$(document.ready(function(){a(); b();});
$(function(){//functions applied to certain elements that does not require to be initially loaded})
有一点进步,但我不满意。如果我只想为某个页面调用某些函数怎么办?有办法做到这一点吗?当我使用很多插件时,我真的很厌恶我的 $(document) 变得非常大。
如何用 jquery 编写函数?
最佳答案
我建议至少对事物进行命名空间以确保不会污染全局命名空间。例如:
var myNameSpace = {
a: function(){//a function that applies plugin to an element},
b: function() {// another function}
};
$(document).ready(function() {
myNameSpace.a();
});
主要好处是您可以将代码划分为专注于特定任务的逻辑工作单元。它将使代码组织变得更加容易。
Rebecca Murphey 就这个主题写了一篇精彩的文章,您可以在这里阅读:http://bit.ly/6og36U
您还可以将 JS 分成自己独特的文件,并编写一个例程来利用 jQuery 的 getScript() 方法按需加载必要的文件 ( http://docs.jquery.com/Ajax/jQuery.getScript )。关键是确定脚本中的依赖关系并在适当的时间加载 .js 文件。
关于javascript - 在 js 中编码时正确的函数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1918801/