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

故事扮演 提交于 2019-11-30 13:19:54

问题


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()');
}); 

回答1:


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.




回答2:


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 :-)




回答3:


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/




回答4:


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

(function (jQuery) {

then to finish...

})(jQuery);

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



来源:https://stackoverflow.com/questions/1158953/four-variations-of-jquery-ready-whats-the-difference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!