开发者

Difference between jQuery code structures

What is the difference between these 开发者_如何转开发jQuery code structures, or is there no difference. Are they both an alias for $(document).ready(function(){ and if so, why the dollar in the first code snippet?

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

AND

$(function() {
        // stuff
});


The $ parameter in the first block is unneeded in that context.

Where you would see it is in a block like this:

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

In that context it would allow you to always use the $ alias even if there was a conflicting library.

Ignoring that, there is no difference. $ is just an alias for jQuery.

Both are shortcuts for $(document).ready(function(){


What BNL said and yes, they are both an alias for $(document).ready(function(){

you could also write jQuery(document).ready(function(){ :)


if you only are using jQuery then both $ and jQuery is the same, but if you are using another javascript library that uses $ as a shortcut then they wont be the same. But if its just jQuery then its just like you and @BNL have written its, its the same.


The first code snipped serves the purpose of avoiding conflicts with other JS libraries that may be using the $ symbol. Wrapping the jQuery code in this manner allows you to use $ inside without worrying about conflicts. It's a good practice e.g. if you are writing a jQuery plugin to protect against conflicts in this manner. Otherwise, normally jQuery is a synonym for $.

Also have a look here for some additional info on avoiding conflicts with other libraries: http://api.jquery.com/jQuery.noConflict/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜