若是我問你window.onload是什麼意思,恐怕你會回答我:「這不是頁面加載完就執行嗎」。
可是答案是不必定,得看你怎麼用。看一下例子吧
例1:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript">
function ShowMessage()
{
alert("true");
}
window.onload=ShowMessage();
</script>
</head>
<body>
當你看到true時看不到我
</body>
</html>
當你看到true的彈出框的時候,你確定沒有看到「當你看到true時看不到我」,說明頁面尚未載入完就已經開始執行js了。
例2
代碼以下:
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<script type="text/javascript">
function ShowMessage()
{
alert("true");
}
window.onload=function(){ShowMessage();}
</script>
</head>
<body>
你看到true時就看到我了
</body>
</html>
當你看到true的彈出框的時候,你也會看到「你看到true時就看到我了」,這個纔是真正的頁面載入完才觸發。
PS:推薦像onload事件之類的使用匿名函數執行,即window.onload=function(){ShowMessage();}這種形式。
參考:腳本之家