jQuery newbie: what does jQuery(function($) { … }) means?

后端 未结 5 1532
旧时难觅i
旧时难觅i 2020-12-13 14:11

I know in jQuery, $(callback) is the same as jQuery(callback) which has the same effect as $(document).ready().

How about

5条回答
  •  半阙折子戏
    2020-12-13 14:52

    When you call the main jQuery factory function (either as jQuery() or the common shortcut $()) it decides what to do based on the type of .

    If you pass a string as it assumes that is a selector specification and will return a jQuery list of elements matching that selector.

    If you pass a jQuery object (representing a list of elements, i.e. an object returned from a previous call to jQuery) it will just return that object (essentially this is a non-operation).

    If you pass it a DOM element it will return a jQuery list containing just that element (so you can apply jQuery methods to that element). This is what is happening with $(document).ready() - you pass the factory function the DOM element "document", it returns a jQuery object representing that element, and you use that object's ready() method to add an event handling function to the ready event of all the DOM elements in the list (just the one, document, in this case).

    If you pass it a function, this is just a shorthand for "run this when everything is ready for you to do so", so $(function() { ... }); is equivalent to $(document).ready(function() { ... });

提交回复
热议问题