我正在尝试使用下面的代码来自动滑动 4 到 5 个图像,这些图像应该一个接一个地连续出现。为此,我使用 for 循环和 setTimeout 编写了下面的代码来将图像延迟到列表末尾。
我在这里面临的问题是,我能够在延迟一段时间后查看图像,但我只能看到列表的最后一个图像,而不是所有图像。
无法追踪问题。
<article id="images" >
</article>
<script>
var ima = ['11.jpg','12.jpg' ];
var txt="'"+"Images/"+ima[0]+"'"; */
var x = document.createElement("IMG");
for (i = 0; i < ima.length; i++) {
var x = document.createElement("IMG");
x.setAttribute("src", "Images/"+ima[i]);
x.setAttribute("width", "200");
x.setAttribute("height", "200");
setTimeout(function(){document.getElementById("images").appendChild(x);}, 1000);
}
</script>
使用上述代码,窗口中仅显示 12.jpg
,但不显示 11.jpg
。
我的期望是:
- 首先,应显示
11.jpg
- 1 秒后,
11.jpg
应该不可见,而12.jpg
应该可见。
最佳答案
<小时/>This is an asynchronous issue.
setTimeout
triggers it callback after the loop has finished running. The value stored inx
will not be different for each iteration of the loop with the code you provided.When setTimeout eventually calls this line:
document.getElementById("images").appendChild(x);
the value of x is going to be whatever the value of x is after the last iteration of the loop. So if you have 5 elements , you'll be making 5 calls to setTimeout where
x.src === "Images"+ima[4]
为了解决这个问题,您可以使用闭包来在调用 x 变量时保持其范围不变:
for (i = 0; i < ima.length; i++) {
var x = document.createElement("IMG");
x.setAttribute("src", "Images/"+ima[i]);
x.setAttribute("width", "200");
x.setAttribute("height", "200");
// create a closure to pass to set interval
appendImg = function(x){
return function(){
document.getElementById("images").appendChild(x);
};
}(x);
// pass closure to setInterval, the x value will be enclosed in the closure for each
//value of x
setTimeout(appendImg, 1000);
}
关于javascript - 最后一张图像显示在 JavaScript 的完整图像列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43260741/