$(document).ready(function(){})和$(document).on('ready',function(e)之间的区别 [英] Differences between $(document).ready(function(){}) and $(document).on('ready', function(e)

查看:305
本文介绍了$(document).ready(function(){})和$(document).on('ready',function(e)之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到许多项目正在使用

I see many projects using

$(document).on('ready', function(e){
 //jquery stuff
})

代替:

$( document ).ready(function(  ) {
  // Code using $ as usual goes here.
});

 $(function() {
  // Handler for .ready() called.
 });

我阅读了完整的 api文档,但是我看不到使用情况是什么第一个例子.

I read the complete api documentation but I don't see what is the case of use of the first example.

对我来说,在第一个示例中使用on是没有用的.

For me, the use of on in the first example is useless.

这两个案例有什么区别?

What are the differences between the cases?

推荐答案

函数:

$( document ).ready(function ( ) {
  // Code using $ as usual goes here.
});

翻译为:

$( document ).on( 'ready', function (e) {
 //jquery stuff
})

这些速记功能相同:

$( element ).click( function ( ) { } );
$( element ).hover( function ( ) { } );
$( element ).load( function ( ) { } );
$( element ).scroll( function ( ) { } );

来自.click( handler(eventObject) )文档:

此方法是前两个变体中的.on( "click", handler )和第三个变体中的.trigger( "click" )的快捷方式.

This method is a shortcut for .on( "click", handler ) in the first two variations, and .trigger( "click" ) in the third.


更新后的答案-有所不同!

还有$(document).on( "ready", handler ),从开始不推荐使用 jQuery 1.8 .行为与ready方法类似,但是如果 ready事件已经触发,您尝试.on( "ready" ) 处理程序将不会执行.准备好以这种方式绑定的处理程序是 在上述其他三种方法的任何约束之后执行.

There is also $(document).on( "ready", handler ), deprecated as of jQuery 1.8. This behaves similarly to the ready method but if the ready event has already fired and you try to .on( "ready" ) the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.

-

更新#2

jQuery(function(){});

也应被认为是

jQuery(document).ready(function(){});

由于它不会降低可读性并删除几个字节的字符,因此是真正的首选.

It is genuinely prefered since it does not reduce readability and removes a few bytes of character.

这篇关于$(document).ready(function(){})和$(document).on('ready',function(e)之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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