2

Possible Duplicate:
What is the difference between these jQuery ready functions?

I have always used:

$(document).ready(function (){
    //Code goes here
});

And inserted my jQuery/JavaScript code therein (so that it waits on the html page to be fully loaded before running any code).

Lately, I have seen this:

jQuery(function($){
    //Code goes here
});

I have searched for what the difference is here (mainly what the 'jQuery' part is all about).

My questions:

  • What does the jQuery part of the latter code block do, if anything?
  • What is the '($)' argument doing for that function?
  • Is there even a difference (other than making the page wait to be loaded) between my two code block examples?
4

4 回答 4

3

The main difference is the closure around the $ variable. The first snippet assumes that the $ variable has not been released (by using .noConflict() or if another library you are using also makes use of $ but not as the jQuery variable).

The second implementation is safer because it doesn't make any assumptions but allows your internal code to safely use the $ variable by making it a parameter.

于 2012-11-28T18:02:12.083 回答
2

It is the same thing:

Using jQuery(function(){}) is just a shorthand for $(document).ready(function (){});

Note: you can use $ or jQuery

于 2012-11-28T18:01:12.117 回答
1

They're the same. From the documentation:

JQuery Call back (jQuery( callback ))

"This function behaves just like $(document).ready(), in that it should be used to wrap other $() operations on your page that depend on the DOM being ready. While this function is, technically, chainable, there really isn't much use for chaining against it."

于 2012-11-28T18:04:17.753 回答
0

They are nearly the same.

In the second function you are passing in jQuery i.e. $ into the function. $ is shorthand for the jQuery.

Straight from the jQuery library code for when you call $()

// tests to see if you passed in a function
} else if (jQuery.isFunction(selector)) { 
    // adds the function to be called when jQuery fires the ready event
    return rootjQuery.ready(selector); 
}

Comments are mine.

于 2012-11-28T18:02:13.067 回答