gpt4 book ai didi

Javascript - 数组循环问题

转载 作者:行者123 更新时间:2023-11-28 20:39:19 24 4
gpt4 key购买 nike

我有以下代码,正常工作时应在 iframe 中打开链接 1,等待 3 秒,然后在 iframe 中打开链接 2,等待 3 秒,依此类推。

目前它直接跳到数组中的最后一个值(最后一个链接)。

有 JS 专家吗?

 <html>
<head></head>
<body>

<a href="http://www.google.com">Google</a><br />
<a href="http://www.thinkgeek.com">ThinkGeek</a><br />
<a href="http://www.themetapicture.com">The Meta Picture</a>

<iframe src="http://www.google.com" id="myid" name="main" width="1024" height="768">
</iframe>

<script>
function getLinksArray() {
for (var i = 0; i < document.links.length; i++) {
var linx = document.links[i].href;

// create a closure for each loop iteration
(function(linx) {
setTimeout(function() {
openLinks(linx);
}, 3000);
}(linx));

}
}

function openLinks(link) {
document.getElementById("myid").src = link;
}

window.onload = getLinksArray();
</script>
</body>
</html>

最佳答案

您可能需要 3000 * i 作为延迟,否则所有操作都会在 3000 毫秒(3 秒)后执行。由于它们是连续执行的,所以最后一个是被注意到的。

// ...
setTimeout(function(){
// ...
}, 3000 * i);
// ...

关于Javascript - 数组循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14717558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com