jQuery document ready function

后端 未结 7 1189
南旧
南旧 2020-12-03 17:20

Are the end results of the following jQuery snippets identical?

Snippet 1:

$(function() { alert(\'test!\'); });

相关标签:
7条回答
  • 2020-12-03 18:15

    Yes:

    $(document).ready(function() { 
      /* code */
    });
    

    …and:

    $(function() { 
      /* code */
    });
    

    …are effectively the same, and the latter is commonly referred to as shorthand for the former.

    If you're wondering why they produce the same outcome, it has to do with the jQuery constructor—the jQuery() function, aliased as $()and its allowed inputs.

    The constructor is documented at api.jquery.com/jquery/, and its two relevant options are outlined below.


    jQuery( selector [, context ] )

    Accepts a string containing a CSS selector which is then used to match a set of elements.

    Returns a jQuery object.

    This option above is how you're invoking the jQuery constructor when writing:

    $(document).ready(function() { /* code */ });
    

    The document object is selected and used to construct a jQuery object. When the DOM is fully loaded, that jQuery object invokes the callback (the anonymous function) within ready().


    jQuery( callback )

    Binds a function to be executed when the DOM has finished loading.

    Returns a jQuery object.

    This option above is how you're invoking the jQuery constructor when writing:

    $(function() { /* code */ });
    

    The callback function (the anonymous function) is used to construct a jQuery object, and when the DOM is fully loaded, it is invoked.

    0 讨论(0)
提交回复
热议问题