【问题标题】:What's the difference between $(document).ready(…) and $(function() {}) in jQuery? [duplicate]jQuery 中的 $(document).ready(…) 和 $(function() {}) 有什么区别? [复制]
【发布时间】:2012-06-05 09:27:40
【问题描述】:

两者有什么区别:

$(document).ready(function() {// Do something});

$(function() {//Do something});

在 jQuery 中?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    如果我简而言之,它们是别名。它们是等价的。

    注意

    $(document).ready(function() {
    
    })
    
    
    $().ready(function() {
      // this is not recommended
    }) 
    
    $(function() {
    
    });
    

    都是一样的。


    更多

    jQuery 开发者推荐使用:

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

    为什么$().ready()不推荐看Why "$().ready(handler)" is not recommended?

    【讨论】:

      【解决方案2】:
      $(document).ready(handler)
      $().ready(handler) (this is not recommended)
      $(handler)
      

      是等价的。

      实际上,您可以在任何 jQuery 对象上调用.ready(handler),无论它包含什么,它都会做同样的事情:

      ready: function( fn ) {
          // Attach the listeners
          jQuery.bindReady();
      
          // Add the callback
          readyList.add( fn );
      
          return this;
      },
      

      【讨论】:

        【解决方案3】:

        没有。

        来自 jQ API:

        以下三种语法都是等价的:

         $(document).ready(handler)
         $().ready(handler) (this is not recommended)
         $(handler)
        

        http://api.jquery.com/ready/

        【讨论】:

          【解决方案4】:

          它们是相同的(意味着它们做同样的事情)。检查文档中的这些行

          All three of the following syntaxes are equivalent:
          
          $(document).ready(handler)
          $().ready(handler) (this is not recommended)
          $(handler)
          

          实际上$(handler)$(document).ready(handler) 的硬编码快捷方式。在http://code.jquery.com/jquery.js 的源代码中,如果您搜索rootjQuery,您很快就会找到这些行

          // HANDLE: $(function)
                  // Shortcut for document ready
                  } else if ( jQuery.isFunction( selector ) ) {
                      return rootjQuery.ready( selector );
                  }
          

          或查看此链接https://github.com/jquery/jquery/blob/37ffb29d37129293523bf1deacf3609a28b0ceec/src/core.js#L174 了解

          表示如果传递的selector是一个函数,那么它被用作$(document).ready(处理程序。

          http://api.jquery.com/ready/

          同时检查Which JQuery document.ready is better?

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-01-13
            • 2019-07-02
            • 2011-07-08
            • 1970-01-01
            相关资源
            最近更新 更多