jQuery之DOM准备

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>4-1-1</title>
<script type="text/javascript">
  document.getElementById("panel").onclick=function(){
    alert( "元素已经加载完毕 !");
  }
    /*执行错误*/
</script>
</head>
<body>
<div id="panel">click me.</div>
</body>
</html>

因为没有加载。加载过早,还没有晓得哪个是panel,所以会报错。如果用window.onload就会等页面加载完了,再调用相应的函数,这样就能知道哪个是panel了。

修改如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Panel</title>
<script type="text/javascript">
  window.onload = function(){
      document.getElementById("panel").onclick=function(){
        alert( "元素已经加载完毕 !");
      }
  }
</script>
</head>
<body>
<div id="panel">click me.</div>
</body>
</html>

或者用jQuery中的$(document).ready如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Panel</title>
<script src="http://www.cnblogs.com/scripts/jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
  $(document).ready(function(){
       document.getElementById("panel").onclick=function(){
            alert( "元素已经加载完毕 !");
      }
  })
</script>
</head>
<body>
<div id="panel">click me.</div>
</body>
</html>

但是两者又是有区别的,window.onload只能加载一次。而jQuery中的$(document).ready可以加载多次:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript">
 function one(){
   alert("one");
 }
 function two(){
   alert("two");
 } 
 window.onload = one ;
 window.onload = two ;
</script>
</head>
<body>

</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://www.cnblogs.com/scripts/jquery-1.3.1.js" type="text/javascript"></script>
<script type="text/javascript">
  function one(){
   alert("one");
 }
 function two(){
   alert("two");
 } 
  $(document).ready(function(){
      one();
  })
  $(document).ready(function(){
      two();
  })
</script>

</head>
<body>

</body>
</html>
posted @ 2012-09-07 15:03  TBHacker  阅读(285)  评论(0编辑  收藏  举报