0
var backgroundImages = new Array(); // create an array holding the links of each image
        backgroundImages[0] = "style/images/bg0.png"; 
        backgroundImages[1] = "style/images/bg1.png";
        backgroundImages[2] = "style/images/bg2.png";
        backgroundImages[3] = "style/images/bg3.png";
        backgroundImages[4] = "style/images/bg4.png";
        backgroundImages[5] = "style/images/bg5.png";
        backgroundImages[6] = "style/images/bg6.png";

        var ImageCnt = 0;

        function nextImage(direction) // this should take into account the current value (starts at 3) and determines whether a higher or lower value should be returned based on the direction
        {
            if(direction == "left")
            {
            ImageCnt-- ;
            }
            if(direction == "right")
            {
            ImageCnt++ ;
            }
            document.getElementById("body-1").style.background = 'url(' + backgroundImages[ImageCnt] + ')'; //put's the new background together for rendering by using the returned value from nextImage()
            if(ImageCnt == 6)
            {
                ImageCnt = -1;
            }
        }

在此脚本中,ImageCnt ++ 在函数“nextImage('right')”上工作正常,但在触发 ImageCnt-- 的 nextImage('left') 上,函数中断。我究竟做错了什么?(js新手)

4

1 回答 1

1

好吧,您的“换行”代码说要使其为-1,但是如果我向左走怎么办?它将尝试访问不存在的-2。

试试这个:

ImageCnt = (ImageCnt + (direction == "left" ? backgroundImages.length-1 : 1)) % backgroundImages.length;
document.getElementById("body-1").style.background = "url('"+backgroundImages[ImageCnt]+"')";

另请注意,像这样逐个构建数组的效率非常低。尝试这个:

var backgroundImages = [
  "style/images/bg0.png",
  "style/images/bg1.png",
  "style/images/bg2.png",
  "style/images/bg3.png",
  "style/images/bg4.png",
  "style/images/bg5.png",
  "style/images/bg6.png",
];
于 2013-09-18T22:10:57.817 回答