JS快速学习之head和body的中变量初始化问题

    技术2023-05-16  91

    js script放在head跟body里面的区别

    在head中时,所代表的functions只加载而不执行,执行是在某一事件触发后才开始。 在body中时,直接加载并执行 典型区别:如果有不在函数中的执行语句,比如变量初始化,如果在head中就不会执行。

    例如:

    <html> <head> <title>第一个Html5视频测试</title> <script type="text/javascript"> var myVideo=document.getElementById("video1"); function playPause() { if (myVideo.paused) myVideo.play(); else myVideo.pause(); } </script> </head> <body> <div style="text-align:center;"> <button onclick="playPause()">播放/暂停</button> <br/> <video id="video1" src="mov_bbb.ogg" width="320" height="240" controls="controls"> Your browser does not support the video tag. </video> </div> </body> </html>

    点击“播放/暂停”时,playPause会被执行,但执行时myVideo对象没有定义的,因为定义和初始化语句被有执行过。

    如果要执行,需要放在body

    <html> <head> <title>第一个Html5视频测试</title> </head> <body> <div style="text-align:center;"> <button onclick="playPause()">播放/暂停</button> <br/> <video id="video1" src="mov_bbb.ogg" width="320" height="240" controls="controls"> Your browser does not support the video tag. </video> </div> <script type="text/javascript"> var myVideo=document.getElementById("video1"); function playPause() { alert("AA"); if (myVideo.paused) myVideo.play(); else myVideo.pause(); } </script> </body> </html>
    Processed: 0.010, SQL: 10