手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >jQuery中$(function() {});问题详解
jQuery中$(function() {});问题详解
摘要:$(document).ready()里的代码是在页面内容都加载完才执行的,如果把代码直接写到script标签里,当页面加载完这个scrip...

$(document).ready() 里的代码是在页面内容都加载完才执行的,如果把代码直接写到script标签里,当页面加载完这个script标签就会执行里边的代码了,此时如果你标签里执行的代码调用了当前还没加载过来的代码或者dom,那么就会报错,当然如果你把script标签放到页面最后面那么就没问题了,此时和ready效果一样。

$(document).ready(function(){})可以简写成$(function(){});

点击段落后,此段落隐藏:

<html> <head> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ $("p").click(function(){ $(this).hide(); }); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> </body> </html>

如果把$(document).ready(function() {});去掉后,无法隐藏段落:

<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $("p").click(function(){ $(this).hide(); }); </script> </head> <body> <p>If you click on me, I will disappear.</p> </body> </html>

但是把script放到页面最后的话,就可恢复隐藏效果:

<html> <head> </head> <body> <p>If you click on me, I will disappear.</p> </body> <script type="text/javascript" src="jquery-1.7.2.min.js"></script> <script type="text/javascript"> $("p").click(function(){ $(this).hide(); }); </script> </html>

总结:

$(document).ready 里的代码是在页面内容都加载完才执行的,你直接写到script标签里,当页面加载完这个script标签就会执行里边的代码了,如果你标签里执行的代码调用了当前还没加载过来的代码或者dom,那么就会报错,

当然如果你把script标签当到页面最后面那么就没问题了和ready差不多的效果

【jQuery中$(function() {});问题详解】相关文章:

JavaScript function函数种类详解

JQuery中层次选择器用法实例详解

AngularJS中$interval的用法详解

JavaScript中的acos()方法使用详解

JavaScript的document和window对象详解

JavaScript中的lastIndexOf()方法使用详解

jQuery 遍历函数详解

JQuery中DOM事件绑定用法详解

jQuery中 prop() attr()使用详解

JQuery boxy插件在IE中边角图片不显示问题的解决

精品推荐
分类导航