<head> <title></title> <style type="text/css"> div{background-color:#efddfe; width:400px; height:20px } </style> <script src="jquery-1.7.1.js" type="text/javascript"></script> <script type="text/javascript"> alert(i); var i = "head內定義變量"; alert(i); </script> <script type="text/javascript"> alert(i); </script> </head> <body> <div> <script type="text/javascript"> document.write(i); document.write(j); </script> </div> <div> <script type="text/javascript"> var j = "body內定義的變量"; document.write(i); document.write(j); </script> </div> <div> <script type="text/javascript"> document.write(i); document.write(j); </script> </div> </body> </html>
javascript中,變量定義的位置與寫在哪一個<script></script>標籤對內無關,只分先後順序,寫在前面的後面就可以訪問,寫在後面的前面會提示「未定義」。javascript
例如:在頁面頂部<head>標籤對內定義的變量,在頁面任意地方都能用。可是在頁面<body>內部定義的變量,就只能在其後面的地方的可以使用。css