javascript - 在 js 中编码时正确的函数顺序

标签 javascript jquery

我正在使用 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/

相关文章:

javascript - 如何完全禁用所有 Internet Explorer 脚本错误对话框

javascript - 尝试找出如何使用 "this"寻址各个菜单项

javascript - ajax 加载后 setInterval javascript 调用不会消失

javascript - jQuery 多选下拉菜单,带有所选项目的关闭按钮

javascript使函数内的变量成为全局变量

javascript - HighCharts图表导出(截图下载)不显示Navigator图

javascript - 去除 iFrame 的 html 标签样式

javascript - 纯 javascript 检查是否有东西悬停(不设置鼠标悬停/移出)

jQuery 调整丢失边框的大小

javascript - 滑动下拉菜单