JavaScript:window.onload问题

前几天做一个点击按钮,就实现切换图片效果的小demo时,代码看上去没问题,就是达不到效果。让我百思不得其解。

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

        <img src="img/1.png"/>
        <input type="button" id="btn" value="改变图片" onclick="changePic()" />

    </body>

    <script type="text/javascript">
        window.onload=function(){
            //1.获取img标签
            var img=document.getElementsByTagName("img");
            //2.定义count来存对应图片---图片名字分别为1,2,3,4
            var count=2;
            //3.切换图片函数
            function changePic(){
                if(count<4){
                    img[0].src="img/"+count+".png"; 
                    count++;
                }else if(count==4){
                    img[0].src="img/"+count+".png";
                    count=1;
                }
            }
        }

    </script>
</html>

一直以来,我们写前端代码时,第一件事就是写window.onload的呀!为什么会出问题呢?

后来,上网去查,才得知是因为changePic()放在window.onload中就变成了一个局部函数了,不能实现在标签中的直接调用。

去掉window.onload就可以使用了。

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

        <img src="img/1.png"/>
        <input type="button" id="btn" value="改变图片" onclick="changePic()" />

    </body>

    <script type="text/javascript">

        //1.获取img标签
        var img=document.getElementsByTagName("img");
        //2.定义count来存对应图片---图片名字分别为1,2,3,4
        var count=2;
        //3.切换图片函数
        function changePic(){
            if(count<4){
                img[0].src="img/"+count+".png"; 
                count++;
            }else if(count==4){
                img[0].src="img/"+count+".png";
                count=1;
            }
        }       
    </script>
</html>

如果你非要用window.onload,就使用–对象.函数–的方法

代码如下:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>

        <img src="img/1.png"/>
        <input type="button" id="btn" value="改变图片" />

    </body>

    <script type="text/javascript">
        window.onload=function(){
            //1.获取img标签
            var img=document.getElementsByTagName("img");
            //2.定义count来存对应图片---图片名字分别为1,2,3,4
            var count=2;
            //3.切换图片函数
            document.getElementById("btn").onclick=function(){
                if(count<4){
                    img[0].src="img/"+count+".png"; 
                    count++;
                }else if(count==4){
                    img[0].src="img/"+count+".png";
                    count=1;
                }
            }
        }
    </script>
</html>
posted @ 2017-05-05 20:36  TCB_Java  阅读(254)  评论(0编辑  收藏  举报