jQuery ready函数别名 [英] jQuery ready function aliases
问题描述
对于创建新jQuery对象的所有不同方式,我有些困惑.
I'm a little confused about all the different ways to create a new jQuery object.
相关文档似乎是: http://api.jquery.com/ready/ http://api.jquery.com/jQuery/
the relevent docs seem to be: http://api.jquery.com/ready/ http://api.jquery.com/jQuery/
在这两个文档中,以下内容都是等效的(别名或不别名'$'除外):
From those two docs the following are all equivalent, (with the exception of aliasing or not aliasing '$'):
- $(document).ready(handler)
- $().ready(handler)
- $(处理程序)
- jQuery(function($){});
- jQuery(document).ready(function($){});
那是正确的吗?我有想念吗?
Is that correct? Did I miss any?
推荐答案
嗯,还有另一个.从文档中:
Well, there is another. From the docs:
也有 $(document).bind("ready",handler). 这与ready
的行为类似 方法,但有一个例外:如果 准备就绪的事件已经触发,您 尝试.bind("ready")边界 处理程序将不会执行.
There is also $(document).bind("ready", handler). This behaves similarly to the ready
method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed.
其他初始化程序方法将始终运行...因此,例如,您可能会发现自己在多个文件中声明了$(document).ready(function() { //stuff }
,并且该处理程序始终处于运行状态.
The other initialiser methods will always run... so you might find yourself declaring $(document).ready(function() { //stuff }
in a number of files for example, and the handler is always run.
我经常会使用jQuery(document).ready(function($) {})
或$(document).ready(function() {})
...我发现它们更具可读性.
I'd go with jQuery(document).ready(function($) {})
or $(document).ready(function() {})
more often than not... I find that they're more readable.
另一种方法是在结束body标记之前调用脚本,并在脚本中执行类似的操作,
Another approach would be to call a script just before the closing body tag and in it do something like,
(function($) {
//stuff
})(jQuery);
如果需要避免与使用$的其他库冲突.这是一个自动执行的匿名函数,它使您可以在别名范围内使用别名,而不必担心与其他库发生冲突.
if you need to avoid conflicts with other libraries using $. This is a self-executing anonymous function and it lets you use the alias in its scope without fear of conflicts from other libraries.
这篇关于jQuery ready函数别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!