I know in jQuery, $(callback)
is the same as jQuery(callback)
which has the same effect as $(document).ready()
.
How about
jQuery(function($) { });
Can some one explain to me what does this kind of function mean?
What does it do?
what is the difference between this one and $(callback)
??
what is the difference between this one and $(function())
??
(function($) { // do something })(jQuery); this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $ .
At its core, jQuery is used to connect with HTML elements in the browser via the DOM. The Document Object Model (DOM) is the method by which JavaScript (and jQuery) interact with the HTML in a browser. To view exactly what the DOM is, in your web browser, right click on the current web page select “Inspect”.
Answer: Use the syntax $. fn. myFunction=function(){}
jQuery(function($) { });
is the safest version of all three. It makes $
the local variable and thus gracefully avoids the conflicts with any other variables which possibly use $
symbol.
I think it was also added fairly recently, don't remember seeing it before.
These function all do the same things - execute some code when DOM is ready. $(document).ready(function(){})
is the original one, and it matches the underlying javascript API.
"$" and "jQuery" which accept function as an arguments were created as shortcuts to avoid repeating such a common construct. Accepting a function which accepts $ as its first argument is a further syntax sugar - now you get convenience of the closures without the need to do it yourself.
$(function())
is a syntax error.$()
creates an empty jQuery object.$(document).ready(function() { ... })
executes the given function when the DOM is ready$(function() { ... })
is a shortcut for the same thingjQuery(function($) { ... })
does so, too, but it also makes $
available inside the function no matter what it's set to outside.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With