Looping Arrays to Change Background Image of Div

问题内容:

I am trying to create a loop of an array that changes the background of a div only one single loop. The code is as follows;

var ImagesF = [];
ImagesF[0]="images/image1.png";
ImagesF[1]="images/image2.png";
ImagesF[2]="images/image3.png";

var i = 1;
var index = 0;
var iterations = 0;
var interval = setInterval(autoImgB(), 2000);

function autoImgB(arr1, id){
var url = 'url(' + arr1 [i] + ')';
if(index >= arr1.length) {
    index = 0;
    iterations++;
}
document.getElementById(id).style.backgroundImage = url;
if (iterations >= 2) {
    clearInterval(interval);
}  else {index++}
}

The code is being called like, onclick="autoImgB(ImagesF, 'DIV')"It seems to be trying to work and it does change the first image, however then it doesn’t seem to be passing the arguments to the next iteration, what am I doing wrong?

问题评论:

答案:

答案1:

setInterval expects a function as its first parameter

var interval = setInterval(function() {
     autoImgB();
}, 2000);

答案评论:

    
This is great information. The error I am receiving is saying that it is “Unable to get property ‘0’ of undefined or null reference”, which gives me the impression it is not passing the ‘(arr1, id)’ originally passed in the function during the iteration. I attempted to add this to the interval but it doesn’t seem to work.
– Brandon
5 secs ago

原文地址:

https://stackoverflow.com/questions/47756237/looping-arrays-to-change-background-image-of-div

添加评论

友情链接:蝴蝶教程