Home  >  Q&A  >  body text

javascript - Why should this zero padding function be placed outside window.onload?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body style="background: black;color: #fff;font-size: 58px;">
    <img src="img/0.png" />
    <img src="img/0.png" />
    :
    <img src="img/0.png" />
    <img src="img/0.png" />
    :
    <img src="img/0.png" />
    <img src="img/0.png" />

    <script>
        function bul(n)
        {
            if(n<10)
            {
                return "0"+n;
            }
            else
            {
                return ""+n;
            }
        }

        window.onload=function()
        {
            var aImg = document.getElementsByTagName('img');
            var tell;
            tell=setInterval(function(){
                var myDate = new Date();
                var str = bul(myDate.getHours())+bul(myDate.getMinutes())+bul(myDate.getSeconds());
                for(var i=0;i<aImg.length;i++)
                {
                    aImg[i].src = "img/"+str[i]+".png";
                }    
            },500)
            
            tell();
        }

    </script>
</body>
</html>

Xiaobai doesn’t quite understand the reason, so I would like to ask seniors to explain it in detail. grateful.

三叔三叔2687 days ago828

reply all(3)I'll reply

  • 黄舟

    黄舟2017-07-05 10:47:30

    Scope issue, put it outside, you can use it regardless of window.onload or window.onunload

    The code placed in window.onload is just to ensure that the page is loaded, that the node actually exists, and that the node will not be unable to be selected

    And your method of operating numbers, without node operations, can be placed inside or outside

    reply
    0
  • 欧阳克

    欧阳克2017-07-05 10:47:30

    window.onload event is executed when the page is completely loaded

    $(function(){ }) is executed after the tags on the page are loaded

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-07-05 10:47:30

    It can be used inside or outside. It can be shared when placed outside. It can only be used inside the onload event when placed inside.

    reply
    0
  • Cancelreply