小编use*_*704的帖子

Javascript变量未定义

<html>
<head>
    <title>Array of images</title>
    <script type="text/javascript">
        var myPics = new Array[3];
        myPics[0] = "./img/blue.png";
        myPics[1] = "./img/red.png";
        myPics[2] = "./img/yellow.png";
        var counter = 0;

        function preImg(){
        alert(counter);
            if(counter == 0)
                counter = 4;

            counter --;
        alert(counter);
            document.getElementById("coloredImg").src = myPics[counter];
        }

        function nextImg(){
            if(counter == 3)
                counter = -1;

            counter ++;

            document.getElementById("coloredImg").src = myPics[counter];
        }
    </script>
</head>
<body>
    <img src="./img/blue.png" id="coloredImg" alt="Image not found"/>
    <input type="button" onclick="preImg()" value="Previous"/>
    <input type="button" onclick="nextImg()" value="Next"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是我的计数器变量在函数内部未定义.例如,当我调用函数preImg时,它会使用undefined警告我(当它应该只是0时),第二个警告显示NaN时它应该是3.为什么我的函数不识别我的"var counter"它是全局的不是吗?你认为变量mypics会发生同样的情况吗?谢谢!

html javascript variables

3
推荐指数
1
解决办法
267
查看次数

标签 统计

html ×1

javascript ×1

variables ×1