jquery 文档内部或外部的函数准备就绪 [英] functions inside or outside jquery document ready

查看:27
本文介绍了jquery 文档内部或外部的函数准备就绪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我只是将我所有的 jQuery 优点放在 $(document).ready() 函数中,包括在某些用户交互中使用的简单函数.

Up until now I just put all my jQuery goodness inside the $(document).ready() function, including simple functions used in certain user interactions.

但是不需要加载 DOM 文档或只在之后调用的函数也可以放在 $(document).ready() 之外.例如,考虑一个非常简单的验证函数,例如:

But functions that don´t require the DOM document to be loaded or are only called afterwards anyway, can be placed outside the $(document).ready() as well. Consider for example a very simple validation function such as:

function hexvalidate(color) {
// Validates 3-digit or 6-digit hex color codes 
 var reg = /^(#)?([0-9a-fA-F]{3})([0-9a-fA-F]{3})?$/;
 return reg.test(color);
}

该函数仅在 $(document).ready() 函数中调用.

The function is only called from within the $(document).ready() function though.

什么是最佳实践(语法、速度);将这样的函数insideoutside jquery 文档就绪函数?

What is best practice (syntax, speed); placing such a function inside or outside the jquery document ready function?

推荐答案

把它放在里面 这样它就不会污染全局命名空间.由于 JavaScript 的作用域链,它还可以确保更快地解析函数名称.

Put it inside so it won't pollute the global namespace. It also ensures a faster resolve of the function name because of JavaScript's scope chains.

把它放在外面如果它是一个可重用的组件,这样你就可以轻松地将它移动到一个单独的文件中并从不同的上下文中调用.

Put it outside if it's a reusable component so you could easily move it in a separate file and call from different contexts.

由于您已经使用了 JQuery,值得一提的是,在您的情况下,您可能希望将 hexvalidate 定义为 JQuery 插件 外部,然后内部调用它.

Since you already use JQuery, it's worth mentioning, that in your case you may want to define hexvalidate as a JQuery plugin outside and then invoke it inside.

这篇关于jquery 文档内部或外部的函数准备就绪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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