我要做的是:我在一个嵌套数组中迭代,我正确地访问了这个数组,并且我必须及时地完成它。每隔“x”秒,我必须修改一个现有图像的“src”和“rel”(应用淡入淡出),我试图像示例中那样用for循环迭代,但我总是得到最后一个选项,也就是最后一个数组元素
arr = [abc.png, def.png, ghi.png];
for(let i=0; i<3; i++) {
val = arr[i]
setTimeout(function() {
$("#example").html("<img src="+val+ "rel=" +val+ "style='width:100%'>");
}, 1000) }
1条答案
按热度按时间628mspwn1#
您遇到的问题是在1000秒后,当计时器内的代码运行循环时,循环已经再次触发了计时器。此外,您将始终只在循环结束时设置最后一项。原因是您更改了相同的静态元素。
如果我理解正确的话,您希望每x秒更改一次图像
也许像这样的东西能帮上忙
因此,我们使用计时器来确定何时更改图像(每1秒),并使用自调用函数来重复该过程
JavaScript语言:
HTML语言
这是小提琴手https://jsfiddle.net/604rvzpg/