jQuery中$(function() {});问题详解
$(document).ready()里的代码是在页面内容都加载完才执行的,如果把代码直接写到script标签里,当页面加载完这个script标签就会执行里边的代码了,此时如果你标签里执行的代码调用了当前还没加载过来的代码或者dom,那么就会报错,当然如果你把script标签放到页面最后面那么就没问题了,此时和ready效果一样。
$(document).ready(function(){})可以简写成$(function(){});
点击段落后,此段落隐藏:
<html>
<head>
<scriptsrc="http://libs.baidu.com/jquery/1.9.0/jquery.js"type="text/javascript"></script>
<scripttype="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>Ifyouclickonme,Iwilldisappear.</p>
</body>
</html>
如果把$(document).ready(function(){});去掉后,无法隐藏段落:
<html>
<head>
<scripttype="text/javascript"src="jquery.js"></script>
<scripttype="text/javascript">
$("p").click(function(){
$(this).hide();
});
</script>
</head>
<body>
<p>Ifyouclickonme,Iwilldisappear.</p>
</body>
</html>
但是把script放到页面最后的话,就可恢复隐藏效果:
<html>
<head>
</head>
<body>
<p>Ifyouclickonme,Iwilldisappear.</p>
</body>
<scripttype="text/javascript"src="jquery-1.7.2.min.js"></script>
<scripttype="text/javascript">
$("p").click(function(){
$(this).hide();
});
</script>
</html>
总结:
$(document).ready里的代码是在页面内容都加载完才执行的,你直接写到script标签里,当页面加载完这个script标签就会执行里边的代码了,如果你标签里执行的代码调用了当前还没加载过来的代码或者dom,那么就会报错,
当然如果你把script标签当到页面最后面那么就没问题了和ready差不多的效果
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下