jQuery ready function aliases

后端 未结 3 1671
醉话见心
醉话见心 2021-01-05 16:38

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.c

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 16:45

    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.

提交回复
热议问题