开发者

In jQuery, how/why are these three ways of checking that the DOM is setup equivalent?

开发者 https://www.devze.com 2023-01-20 20:08 出处:网络
$(document).ready(function(){}); $(function(){}); jQuery(document).ready(function($){}); I\'m not sure I completely understand what is happening in #2, and why it is equiva开发者_高级运维lent to t
$(document).ready(function(){});

$(function(){});

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

I'm not sure I completely understand what is happening in #2, and why it is equiva开发者_高级运维lent to the standard way of doing it, #1.


jQuery and $ are actually the same.

If you pass a function into the $() function, jQuery basically checks the type of it, and if it's a function, it will execute it when the DOM is ready. It's just Javascript:

function myFunc(arg){
  if(typeof arg == 'function'){
    arg.call();
  }
}

From the jQuery source:

// First, jQuery saves the old values of window.jQuery and window.$

// Map over jQuery in case of overwrite
_jQuery = window.jQuery,

// Map over the $ in case of overwrite
_$ = window.$,

...

// Later on, jQuery returns a reference to the actual jQuery object:
window.jQuery = window.$ = jQuery

...

// and if you use noConflict, it'll replace window.$ (and window.jQuery) with the old values again
noConflict: function( deep ) {
  window.$ = _$;

  if ( deep ) {
    window.jQuery = _jQuery;
  }

  return jQuery;
}

If you call the jQuery function, it'll check the argument type:

init: function( selector, context ) {

  ...

  else if ( jQuery.isFunction( selector ) ) {
    return rootjQuery.ready( selector );
  }

Where rootjQuery is the same as jQuery(document)


A function passed as an argument to the jQuery constructor is bound to the document ready event.

0

精彩评论

暂无评论...
验证码 换一张
取 消