網頁中的某些JavaScript腳本代碼往往需要在文檔加載完成后才能夠去執行,否則可能導致無法獲取對象的情況,為了避免類似情況的發生,可以使用以下兩種方式:
(1).將腳本代碼放在網頁的底端,運行腳本代碼的時候,可以確保要操作的對象已經加載完成。
(2).通過window.onload來執行腳本代碼。
看完下面兩段代碼你就能理解上面的意思了
代碼一
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#bg{
width:100px;
height:100px;
border:2px solid red;
}
</style>
</head>
<body>
<div id="bg"></div>
</body>
</html>
<script type="text/javascript">
document.getElementById("bg").style.backgroundColor="#F90";
</script>
代碼二
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
#bg{
width:100px;
height:100px;
border:2px solid red;
}
</style>
<script type="text/javascript">
window.onload=function(){
document.getElementById("bg").style.backgroundColor="#F90";
}
</script>
</head>
<body>
<div id="bg"></div>
</body>
</html>
看懂了吧 哈哈哈!!!