javascript - Why should this zero padding function be placed outside window.onload?
三叔
三叔 2017-07-05 10:45:30
0
3
831
<!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.

三叔
三叔

reply all(3)
黄舟

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

学霸

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

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

淡淡烟草味

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template