script脚本中写不写$(document).ready(function() {});的差别

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

$(document).ready(function(){})能够简写成$(function(){});


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

<html>
<head>
<script type="text/javascript" src="jquery.js"></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> 



原文地址:https://www.cnblogs.com/gccbuaa/p/6780666.html