Differences between document.ready and $function [duplicate]

帅比萌擦擦* 提交于 2019-12-17 07:29:26

问题


Possible Duplicate:
What is the difference between these jQuery ready functions?
jquery: Choosing a document.ready method

What is the difference between doing this

$(function() {
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

and this

$(document).ready(function(){
    $("a").click(function(event){
        alert("Thanks for visiting!");
    });
});

回答1:


They are the same. Check out the jQuery .ready() docs. Here's a quote from the docs:

All three of the following syntaxes are equivalent:

$(document).ready(handler)

$().ready(handler) (this is not recommended)

$(handler)




回答2:


There is no difference in functionality between your examples - they both bind to DOM ready.

For reference, there are two points at which you can bind your jQuery code.

The first will execute when the DOM is ready (both are equivalent):

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

The second will execute when the page has finished loading all images, stylesheets etc.

$(window).on("load", function() {
   // code
});

The second is useful when you need to get the width() or height() of an image. These properties are only available once the image has completely downloaded to the client system.

Also note that $(window).load(fn); is now deprecated and should no longer be used.




回答3:


All three of the following syntaxes are equivalent:

$(document).ready(handler) 
$().ready(handler) (this is not recommended) 
$(handler) 

http://api.jquery.com/ready/



来源:https://stackoverflow.com/questions/9396415/differences-between-document-ready-and-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!