jQuery中$(function() {});问题详解

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

(document).ready(function()) (function(){});

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<html>
<head>
<script src= "http://libs.baidu.com/jquery/1.9.0/jquery.js" type= "text/javascript" ></script>
<script type= "text/javascript" >
$(document).ready(</code><code class="js keyword">function</code><code class="js plain">(){</code></div><div class="line number6 index5 alt1"><code class="js spaces">&nbsp;</code><code class="js plain">$(</code><code class="js string">"p"</code><code class="js plain">).click(</code><code class="js keyword">function</code><code class="js plain">(){</code></div><div class="line number7 index6 alt2"><code class="js spaces">&nbsp;&nbsp;</code><code class="js plain">$( this ).hide();
  });
});
</script>
</head>
 
<body>
  <p>If you click on me, I will disappear.</p>
</body>
</html>

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<head>
<script type= "text/javascript" src= "jquery.js" ></script>
<script type= "text/javascript" >
  $(</code><code class="js string">"p"</code><code class="js plain">).click(</code><code class="js keyword">function</code><code class="js plain">(){</code></div><div class="line number6 index5 alt1"><code class="js spaces">&nbsp;&nbsp;</code><code class="js plain">$( this ).hide();
  });
</script>
</head>
 
<body>
  <p>If you click on me, I will disappear.</p>
</body>
</html>

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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" >
  $(</code><code class="js string">"p"</code><code class="js plain">).click(</code><code class="js keyword">function</code><code class="js plain">(){</code></div><div class="line number12 index11 alt1"><code class="js spaces">&nbsp;&nbsp;&nbsp;</code><code class="js plain">$( this ).hide();
  });
</script>
</html>

总结:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值