[英]Can someone explain this piece of code to me
这段代码中的字符串是什么意思,它是交通灯脚本的一部分,我不知道每一行是做什么的。
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];
variable
似乎是一个数组,用于存储对图像的引用(URI 或路径),该数组被馈送到图像元素的src
属性<img>
。 脚本简单执行以下逻辑:
index
增加 1index
将图像源设置为variable
数组的第 n 个元素一个聪明的猜测是这是一个图像循环功能。 当nextvariableClick
被调用时,它会按照图像在variable
数组中出现的顺序循环遍历图像列表。
由于脚本如此简单,查看其功能的最佳方法是构建一个函数式代码片段:
// 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);
<p>The function is called at runtime, and called every 1s. You should see cycling of image sources.</p> <img id="starting_light" src="" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.