【问题标题】:Differences between $(document).ready(function(){}) and $(document).on('ready', function(e)$(document).ready(function(){}) 和 $(document).on('ready', function(e) 的区别
【发布时间】:2017-02-18 16:23:37
【问题描述】:

我看到很多项目都在使用

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

代替:

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

或

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

我阅读了完整的api documentation,但我看不到第一个示例的使用情况。

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

案例之间有什么区别?

【问题讨论】:

标签: jquery


【解决方案1】:

功能:

$( 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) )的documentation:

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


更新答案 - 区别!

还有$(document).on( "ready", handler ),已弃用 jQuery 1.8。这与 ready 方法的行为类似,但如果 ready 事件已经触发,你尝试.on( "ready" ) 绑定 处理程序不会被执行。以这种方式绑定的就绪处理程序是 在上述其他三种方法的任意绑定之后执行。

-- Source

更新 #2

jQuery(function(){});

也应该被认为是一个较短的替代

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

它确实是首选,因为它不会降低可读性并删除几个字节的字符。

【讨论】:

  • 不要忘记添加回调,否则将被解释为触发器。 ;-)
  • @Johnツ 当然... :) 谢谢。 :)
  • 那么两者是一回事吗?
  • @EmilioGort 没有区别。 :)
  • @PraveenKumar 在这个问题中他们说不一样..stackoverflow.com/questions/13589307/…
猜你喜欢
  • 1970-01-01
  • 2010-12-11
  • 2011-05-22
  • 2011-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多