Four variations of jQuery ready() — what's the

2020-02-25 23:06发布

I've seen four different ways to tell jQuery to execute a function when the document is ready. Are these all equivalent?

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

$().ready(function () {
  alert('$().ready()');
}); 

$(function () {
  alert('$()');
});     

jQuery(function ($) {
  alert('jQuery()');
}); 

4条回答
够拽才男人
2楼-- · 2020-02-25 23:15

Also it should be mentioned, that symbol that you pass to function will be use inside the function. For example:

$(function(jQuery) {
   // now I can use jQuery instead $
   jQuery("body").append("<div></div>"); // adds div to the end of body element
}); 

if you want use $ - you can leave function's param in this situation empty

The real example you can find here http://jsfiddle.net/yura_syedin/BNgd4/

查看更多
男人必须洒脱
3楼-- · 2020-02-25 23:18

Here's another one - starts like this...

(function (jQuery) {

then to finish...

})(jQuery);

An example is here: http://jsfiddle.net/C2qZw/23/

查看更多
一夜七次
4楼-- · 2020-02-25 23:30

There is no difference.

$ is the same as jQuery. If you view the unminified source, you will see var $ = jQuery = ... or something to that effect.

The jQuery function checks the type of it's parameter, if it is a function, it treats it the same as $(document).ready(...)

Calling jQuery without a parameter defaults to using document. So $() and $(document) are identical. Try it in Firebug.

查看更多
smile是对你的礼貌
5楼-- · 2020-02-25 23:33

re: Geroge IV's comments regarding $() == $(document) its correct. From the unminified source (init is what get called internally):

init: function( selector, context ) {
    // Make sure that a selection was provided
    selector = selector || document;

Also from source, to back up previous conversations:

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

this should be community wiki. I've always been interested in the inner workings of jquery, now I've had an excuse to start looking :-)

查看更多
登录 后发表回答