gpt4 book ai didi

javascript - 在 setInterval 函数中传递计数变量

转载 作者:行者123 更新时间:2023-12-03 01:32:29 24 4
gpt4 key购买 nike

我尝试单步执行数组,并且每 3 秒更改 DOM 中某些项目的innerHTML。此代码当前直接从 0(混合媒体艺术家)到 2(描述符),并且根本不显示 1(艺术教育家)。对于每个 setinterval 循环,console.log 都会输出 0 1 2。

任何人都可以看到我做错了什么才能使其正常工作吗?

var heroItems = ['galleries', 'workshops', 'exhibitions'];
var heroBtns = ['view', 'sign UP', 'VIEW'];
var heroURLs = ['#', '#', '#'];
var descriptions = ['mixed media artist', 'art educator', 'descriptor'];

setInterval(function() {
for (var i = 0; i < descriptions.length; i++){
console.log(i)
changeDescription(i);
}
}, 3000);


function changeDescription(i) {
var descriptor = document.getElementById('descriptor').innerHTML = descriptions[i];
var hero = document.getElementById('hero').innerHTML = heroItems[i];
var heroRef = document.getElementById('heroref').setAttribute('href', heroURLs[i]);
var heroBtn = document.getElementById('herobtn').innerHTML = heroBtns[i];
}

最佳答案

问题是,您不会在每次循环迭代后等待。更改描述 3 次后,您只需等待一次。

就您而言,您也可以完全跳过循环。

var i = 0;
var timer = window.setInterval(function() {
changeDescription(i);
if (++i == descriptions.length) {
window.clearInterval(timer);
}
}, 3000);

关于javascript - 在 setInterval 函数中传递计数变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51226020/

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