1

Any idea why this code is broken or not working? It is not my code but it does appear to be correct, of course I could be missing the obvious. I simply need the background image of a div to cycle to a new one in the/a array ever 5 seconds.

var imageIndex = 0;
var imagesArray = new Array();

//Set Images
imagesArray[0] = "images/self-whitewater.png";
imagesArray[1] = "images/fishing.png";
imagesArray[2] = "images/solo-kayaking.png";

function changeBackground(){
$("main-blocki").css("background","url('"+ imagesArray[imageIndex] +"')");                        
    imageIndex++;
    if (imageIndex > imageArray.length)
        imageIndex = 0; 
}

$(document).ready(function() {
  setInterval("changeBackground()",5000);
});
4

3 回答 3

3

if正如@thatidiotguy 所指定的,您的问题出在您的陈述中。

但是你也可以在一个单行中做到这一点,没有if声明。

var imageIndex = 0;
var imagesArray = [
    "images/self-whitewater.png",
    "images/fishing.png",
    "images/solo-kayaking.png"
];

function changeBackground(){
    var index = imageIndex++ % imagesArray.length;
    $("main-blocki").css("background","url('"+ imagesArray[index] +"')");      
}

$(document).ready(function() {
  setInterval(changeBackground, 5000);
});

注意imageIndex++ % imagesArray.length. 这会增加全局imageIndex值,同时确保该值不大于imagesArray.length.

于 2013-05-14T21:13:28.200 回答
3

你在这里有一个语法错误:

if (imageIndex > imageArray.length)
        imageIndex = 0; 

没有变量调用imageArray

当您遇到语法错误时,您应该使用 Web 调试器向您显示。一个语法错误和 Javascript 可以优雅地杀死您正在运行或尝试运行的所有其他脚本。

于 2013-05-14T21:04:08.363 回答
1
if (imageIndex > imageArray.length)

上面的行是错误的:您应该改为测试imagesArray.length

...并且您还应使用 >= 运算符进行测试,因为索引是基于 0 的

于 2013-05-14T21:05:44.153 回答