2017-10-21 9 views
2

짧은 이야기 이미지 배열에서 4 초마다 이미지를 변경하고 싶습니다. 이 일을 위해 여기에 무엇을 추가해야합니까?Js : 배열을 무한 루프로 반복

var list = ["img1", "img2", "img3"]; 

function ChangeBackground() { 
    document.getElementById('background').src = "images/"+list[i]; 
} 

window.setInterval(ChangeBackground(), 4000); 

답변

4

인덱스에 대해 클로저를 사용할 수 있습니다.

function changeBackground() { 
 
    var i = 0, 
 
     imgURL = 'http://lorempixel.com/250/200/abstract/'; 
 
    return function() { 
 
     document.getElementById('background').src = imgURL + list[i++]; 
 
     i %= list.length; // prevent looping over the length 
 
    }; 
 
} 
 

 
var list = [3, 1, 4, 7]; 
 

 
setInterval(changeBackground(), 4000); 
 
//       ^^   with brackets for returning function
<img id="background">

0

시도 :이 네임 스페이스를 오염 않는다는 것을

var list = ["img1", "img2", "img3"]; 
var i=0; 
function ChangeBackground() { 
    i++; 
    if(i>list.length-1){ 
     i=0; 
    } 
    document.getElementById('background').src = "images/"+list[i]; 
} 

window.setInterval(ChangeBackground(), 4000); 

참고.

0
var list = ["img1", "img2", "img3"], 
    i = 0;               // declare and initialize i outside of the function 

function ChangeBackground() { 
    document.getElementById('background').src = "images/" + list[i]; 
    i = (i + 1) % list.length;          // increment i after each call to this function (make sure i come back to 0 if it exceeds the length of the array using the modulo % operator) 
} 

window.setInterval(ChangeBackground, 4000);       // pass a reference to the function not its return value (notice there is no parens after the function name) 
+0

고맙습니다! 이것은 내가 알고 싶었던 모든 것에 응답했다. ^^ – 888666111