jQuery ready function aliases

2019-02-13 17:35发布

问题:

I'm a little confused about all the different ways to create a new jQuery object.

the relevent docs seem to be: http://api.jquery.com/ready/ http://api.jquery.com/jQuery/

From those two docs the following are all equivalent, (with the exception of aliasing or not aliasing '$'):

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

Is that correct? Did I miss any?

回答1:

Well, there is another. From the docs:

There is also $(document).bind("ready", handler). This behaves similarly to the ready
method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed.

The other initialiser methods will always run... so you might find yourself declaring $(document).ready(function() { //stuff } in a number of files for example, and the handler is always run.

I'd go with jQuery(document).ready(function($) {}) or $(document).ready(function() {}) more often than not... I find that they're more readable.

Another approach would be to call a script just before the closing body tag and in it do something like,

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

if you need to avoid conflicts with other libraries using $. This is a self-executing anonymous function and it lets you use the alias in its scope without fear of conflicts from other libraries.



回答2:

These are somewhat equivalent:

  • $(document).ready(handler) - tuns the handler when the DOM is loaded
  • $().ready(handler) - runs the handler when the DOM is loaded (deprecated, don't use)
  • $(handler) - runs the handler then the DOM is loaded - shortcut to $(document).ready(handler)
  • jQuery(function($) {}) same as #3 above, just using jQuery instead of the $ alias
  • jQuery(document).ready(function($) {}) - same as the first, again using jQuery instead of the $ alias

If $ is defined as something else, e.g. Prototype, then the first 3 won't work. The last 2 are similiar they're just accepting the first argument passed in (the jQuery object) and making it $ inside, making it possible to do this even when $ is something else:

jQuery(function($) {
  $("input").val("something");
});


回答3:

Well if you are only using jQuery then $() is equivalent to jQuery(). So that covers half of them.

Then, if you use $() instead of $(document).ready, those are the same. In this case, it is just a helper function. You may want to add ready on something else for example, in which case, you would do: $(foo).load({})

Last, I don't know what you mean with $().ready because you have to pass a parameter.