开发者

$(document).ready(function() VS $(function(){ [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

what is difference of $(function(){ }); and $(document).ready(function() { }) ;?

What are the differences between $(document).ready(function(){}) vs $(function(){}) and should I write it in the $ form or the new jQuery(document).ready(function(){ }) way?

If I have google api loaded is google.setOnLoadCallback(function() { a better way? or is it the same thing?

I've also seen people use $(function($){})

Can somebody help me, I'开发者_开发技巧m lost. I bugs me when I don't know the code I write. I guess I should read through the library. Are the all being defined as the same thing?


The two ways are equivalent, I personally prefer the second, $(function() {}); it's just a shortcut for document ready.

About the new jQuery(document)... construct, you don't really need to use the new operator, jQuery will use it internally if you don't.

The argument that the ready handler function receives, is the jQuery object itself.

That's quite useful where you have to run jQuery in compatibility mode with other libraries, for example:

jQuery(function ($) {
  // use $ here
});

The $ argument inside the callback will refer to the jQuery object, outside that function it might refer to another library like PrototypeJS.


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

The two statements are actually the exact same. So the second call is just a shortcut for the first.

The $ notation is again only a shortcut for jQuery. If you have loaded jQuery into your website you can use both. Especially if you don't load other JS librarys, which maybe also use the $ sign. That brings us to your mentioned

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

call. What is done here is to make sure, that within your created function expression the $ sign references to the jQuery object. You're calling that anonymous function (which has $ as parameter) and pass the jQuery object in.


I encourage to read some articles that are very useful to understand somethings in jQuery ( and of course in javascript ), this articles explain how to create a jQuery plugin, but reading it you will understand some basic and important things, like closures witch is the meaning in this (function($){}(jQuery)); statement.

http://www.authenticsociety.com/blog/jQueryPluginTutorial_Beginner

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜