有人可以向我解释这段代码

时间:2017-01-21 15:06:28

标签: javascript

此代码中的字符串是什么意思,它是交通灯脚本的一部分,我不知道每条线路的作用。

var index = 0;
var variableLen = variable.length;

function nextvariableClick() {
    index++;

    if (index == variableLen) 
        index = 0;

    var image = document.getElementById('starting_light');
    image.src = variable[index];

1 个答案:

答案 0 :(得分:1)

variable似乎是一个存储图像引用(URI或路径)的数组,它被提供给图像元素的src属性<img>。简单的脚本执行以下逻辑:

  • 触发该功能时,它会将index增加1
  • 如果index等于图像数量,则将其返回0(基本上&#34;循环&#34;通过数组
  • 您可以通过索引variable
  • 将图像源设置为index数组的第n个元素

智能猜测是这是一个图像循环功能。调用nextvariableClick后,它会按照它们在variable数组中的显示顺序循环显示图像列表。

由于脚本非常简单,因此查看其功能的最佳方法是构建功能代码段:

&#13;
&#13;
// Define dummy image references
var variable = [
  'https://placehold.it/500x300/e41a1c/ffffff',
  'https://placehold.it/500x300/377eb8/ffffff',
  'https://placehold.it/500x300/4daf4a/ffffff',
  'https://placehold.it/500x300/984ea3/ffffff',
  'https://placehold.it/500x300/ff7f00/ffffff'
];

/* Start of code you have provided */
var index = 0;
var variableLen = variable.length;

function nextvariableClick() {
  index++;

  if (index == variableLen)
    index = 0;

  var image = document.getElementById('starting_light');
  image.src = variable[index];

}
/* End of code you have provided */

// We execute the function to start initialise it, and set a starting image
nextvariableClick();
window.setInterval(nextvariableClick, 1000);
&#13;
<p>The function is called at runtime, and called every 1s. You should see cycling of image sources.</p>
<img id="starting_light" src="" />
&#13;
&#13;
&#13;