按下按钮后循环整个阵列

时间:2016-11-15 17:48:41

标签: javascript html arrays

总结一下我目前的努力,我制作了一个非常基本的程序,按下按钮后,移动到红绿灯的下一部分(从红色开始,按下琥珀色等),作为每个图像交通信号灯存储在一个数组中。这确实按预期工作,但我现在需要更改此代码以使其按下按钮,而不是仅仅转到数组中的下一个内容,它会循环遍历所有这些代码一段时间,模拟红绿灯。我不能为我的生活找到从哪里开始,我尝试过的所有事情(setTimeoutsetInterval)都没有按预期工作。

这是我的代码(没有任何添加/更改):

<!DOCTYPE html>
<html>
<body>

<h1 style="font-size:300%">Changing Traffic Lights</h1>
<p> 
<button type="button" onclick="changeLights()">Change Lights</button>
</p>

<img id="light" src="traffic-light-red.jpg">

<script>
var list = [
    "traffic-light-red.jpg",
    "traffic-light-amber.jpg",
    "traffic-light-green.jpg"
];

var index = 0;

function changeLights() {
    index = index + 1;      
    if (index == list.length) 
    index = 0;      
    var image = document.getElementById('light');     
    image.src=list[index];
}

</script>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

这样的东西?

&#13;
&#13;
// Array of light images:
var list = [
    "traffic-light-red.jpg",
    "traffic-light-amber.jpg",
    "traffic-light-green.jpg"
];

// Counter to keep track of which image is displayed
var index = 0;

// Get DOM references:
var btnStart = document.getElementById("btnChange");
var image = document.getElementById('light'); 

// Variable to keep track of timer
var timer = null;

// Wire click events for buttons:
btnStart.addEventListener("click", changeLights);

function changeLights() { 
    // Only continue if we haven't cycled through all the 
    // items in the array yet
    if(index < list.length-1){
      
        // Make this function call itself again in approx. 1.5 seconds
        timer = setTimeout(changeLights, 1500);    
    }
    
    // Change the image source and alternate text
    image.src = list[index];
    image.alt = list[index];

    index++;  // Bump up index  
}
&#13;
<h1 style="font-size:300%">Changing Traffic Lights</h1>
<p> 
<button type="button" id=btnChange>Change Lights</button>
</p>
<img id="light" src="traffic-light-red.jpg" alt="traffic-light-red.jpg">
&#13;
&#13;
&#13;