***先告訴大家頁面是自上而下按順序加載的 link->js->body
<!doctype html>
<html>
<meta charset="utf-8">
<title>頁面內(nèi)容執(zhí)行順序</title>
?<script >
? ? ? ? ?function show(){
? ? ? ? ? ? ? ? ? ? ?alert(1);
? ? ? ?};
? ? ?var oBtn=document.getElementById('btn');
? ? ?oBtn.onclick=show;//千萬別加括號,加了括號它會先調(diào)用函數(shù)
</script>
</head>
<body>
? ? ? <input type="button" value="點擊" id="btn"/>
</body>
</html>
? ? ? ? ? ? 頁面中的js腳本在head中,js腳本要讀取的input的在body中。瀏覽器對html頁面的加載是按順序加載的,也就在html中上面的先加載,因此當(dāng)加載到j(luò)s腳本時,input還沒有加載到瀏覽器頁面中。js是一種解釋性的腳本,也是從上而下順序執(zhí)行,由于這段js代碼是立即執(zhí)行的,所以當(dāng)js在執(zhí)行的時候,所以讀取不到input。
最直接的方法是把js放到網(wǎng)頁的最下面執(zhí)行。
<!doctype html>
<html>
<meta charset="utf-8">
<title>頁面內(nèi)容執(zhí)行順序</title>
</head>
<body>
? ? ? ?<input type="button" value="點擊" id="btn"/>
<script>
? ? ? ?function show(){
? ? ? ? ? ? alert(1)
? ? ? ?};
? ? ? ? ? ?var oBtn=document.getElementById('btn');
? ? ? ? ? ? oBtn.onclick=function(){
? ? ? ? ? ? ? ? ? ? ? ?show();
? ? ? ? ? ?};
</script>
</body>
</html>
? ? ? ? ?把js放到網(wǎng)頁最下面,這樣js在執(zhí)行的時候網(wǎng)頁內(nèi)容都已加載完畢。把js放到網(wǎng)頁下面加載并不是最好的解決方法,大部分情況js并不是總能放在網(wǎng)頁的最下面,這時候可以用window 的onload事件,onload事件在整個頁面加載完之后才觸發(fā),可以把js腳本放在onload里面執(zhí)行。
<!doctype html>
<html>
<meta charset="utf-8">
<title>網(wǎng)頁內(nèi)容執(zhí)行的順序</title>
<script>
? ? ? ? window.onload=function(){ ? ? ? ? ?
? ? ? ? ? ? ?var oBtn=document.getElementById('btn'); ??
? ? ? ? ? ? ? oBtn.onclick=function(){
? ? ? ? ? ? ? ? ? ?alert(1);
? ? ? ? ? ? ?};
? ? ? ?};
</script>
</head>
<body>
? ? ? <input type="button" value="點擊" id="btn"/>
</body>
</html>
上面方法本質(zhì)是添加onload監(jiān)聽事件