JQuery predefined function aliases

I got a little confused in all the different ways of creating a new jQuery object.

The relevant documents are as follows: http://api.jquery.com/ready/ http://api.jquery.com/jQuery/

Of these two documents, all are equivalent (except for smoothing or not smoothing '$'):

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

It is right? Have I missed anything?

+6
jquery alias document-ready
source share
3 answers

Well, there is one more. From the docs:

There is also $ (document) .bind ("ready", a handler) . This behaves similarly to a ready-made one, with one exception: if a ready-made event is already running, and you try .bind ("ready"), the associated handler will not be executed.

Other initialization methods will always be executed ... so you can find the declaration $(document).ready(function() { //stuff } in several files, for example, and the handler always starts.

I would more often meet with jQuery(document).ready(function($) {}) or $(document).ready(function() {}) ... I think they are more readable.

Another approach would be to call the script immediately before the closing body tag and do something like

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

if you need to avoid conflicts with other libraries with $. This is a standalone anonymous function, and it allows you to use an alias in your field without fear of conflicts from other libraries.

+3
source share

They are somewhat equivalent:

  • $(document).ready(handler) - configure handler when loading the DOM
  • $().ready(handler) - starts handler when loading the DOM ( deprecated , not using)
  • $(handler) - launches handler , then loads the DOM - shortcut to $(document).ready(handler)
  • jQuery(function($) {}) the same as # 3 above, just using jQuery instead of the $ alias
  • jQuery(document).ready(function($) {}) is the same as the first, again using jQuery instead of the $ alias

If $ defined as something else, for example. Prototype, then the first 3 will not work. The last 2 are similar, they just take the first argument passed to (the jQuery object) and make it $ inside, which allows you to do this even if $ is something else:

 jQuery(function($) { $("input").val("something"); }); 
+4
source share

Well, if you use only jQuery, then $ () is equivalent to jQuery (). So half of them.

Then, if you use $ () instead of $ (document) .ready, then the same. In this case, this is just an auxiliary function. For example, you might want to add something else, for example, in this case: $ (foo) .load ({})

Finally, I don't know what you mean with $ (), because you need to pass a parameter.

0
source share

All Articles