我如何制作时间顺序?

时间:2016-06-21 09:16:06

标签: javascript

我想帮助在代码中添加自动序列。我很感激为这项任务提供任何形式的帮助,如果问题已经完成,我将不胜感激。 这是我到目前为止所做的红绿灯阵列:

<DOCTYPE html>
<html>
<body>
<img id="img" src="./Programming/images/Traffic light 1.jpg"/>
</body>
<button onclick="changingimg()" type="button">Click Here!</button>

<script>

var array = [
    "./Programming/images/Traffic light 1.jpg",
    "./Programming/images/Traffic light 2.jpg",
    "./Programming/images/Traffic light 3.jpg"];
var arrayindex = 0;
var arraylength= array.length;
function changingimg(){
         document.getElementById('img').src = array[arrayindex]
                  if(arrayindex == (arraylength-1)){
                  arrayindex=0;}
                  else{++arrayindex;}
}
</script>
</body>
</html>

由于

1 个答案:

答案 0 :(得分:0)

使用getElementById只需一次(如果已加载),最后我会写它

var array = [
    "./Programming/images/Traffic light 1.jpg",
    "./Programming/images/Traffic light 2.jpg",
    "./Programming/images/Traffic light 3.jpg"],
    arrayindex = 0,
    arraylength= array.length,
    img = document.getElementById('img'),
    interval = 2000;
setTimeout(function (){
      img.src = array[arrayindex++ % arraylength];
}, interval);