有什么不同

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

and

$(window).load(function(){
  //my code here
});

我想确保:

$(document).ready(function(){

}) 

and

$(function(){

}); 

and

jQuery(document).ready(function(){

});

都是一样的。

你能告诉我它们之间有什么异同吗?


当前回答

文档。ready是一个jQuery事件,它在DOM准备好时运行,例如,所有的元素都在那里可以找到/使用,但不一定是所有的内容。 窗口。Onload稍后(或在最坏/失败的情况下同时)在图像等加载时触发。例如,如果你在使用图像尺寸,你通常会想用这个代替。

同时阅读相关问题: $(window).load()和$(document).ready()函数之间的区别

其他回答

ready事件总是在加载到浏览器的唯一html页面时执行,函数执行.... 但是加载事件是在页面.....的所有页面内容加载到浏览器时执行的 我们可以在jQuery脚本中使用noconflict()方法时使用$或jQuery…

来自jQuery API文档

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts. In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.


第二个问题的答案是

不,只要你不是在无冲突模式下使用jQuery,它们是相同的。

文档。ready是一个jQuery事件,它在DOM准备好时运行,例如,所有的元素都在那里可以找到/使用,但不一定是所有的内容。 窗口。Onload稍后(或在最坏/失败的情况下同时)在图像等加载时触发。例如,如果你在使用图像尺寸,你通常会想用这个代替。

同时阅读相关问题: $(window).load()和$(document).ready()函数之间的区别

$(document).ready()和$(window).load()函数之间的区别是,$(window).load()中包含的代码将在整个页面(图像,iframes,样式表等)加载后运行,而document ready事件在所有图像,iframes等加载之前触发,但在整个DOM本身准备好之后。


$(document).ready(function(){

}) 

and

$(function(){

});

and

jQuery(document).ready(function(){

});

以上3个代码没有区别。

它们是等价的,但是如果任何其他JavaScript框架使用相同的美元符号$作为快捷方式名,您可能会面临冲突。

jQuery.noConflict();
jQuery.ready(function($){
 //Code using $ as alias to jQuery
});

这三个功能是相同的:

$(document).ready(function(){

}) 

and

$(function(){

}); 

and

jQuery(document).ready(function(){

});

这里$用于定义jQuery,例如$ = jQuery。

不同之处在于

美元(文档)。ready是加载DOM时触发的jQuery事件,因此它在文档结构准备好时触发。 美元(窗口)。加载事件是在整个内容加载后,如页面包含图像,css等。