我有这个数组:
let learning = [
"HTML",
"CSS",
"JavaScript",
"JQuery",
"Git",
"GitHub",
"Bootstrap",
"Sass",
"JSon"
];
并希望在带有 id="learning-here"
的 span 元素中逐一显示它们我尝试过这样的:
for (const iterator of learning) {
setTimeout(writeList(iterator), 1000);
}
function writeList(i) {
$("#learning-here").text(i);
console.log(i);
}
看来 setTimeout 并没有像我想象的那样工作。当我重新加载页面并且整个数组被控制台记录时,数组上的最后一项就会显示在 span 上。
还用我可怜的 JQuery 知识尝试过,如下所示:
$.each(learning, function(key, value) {
setTimeout(writeList, 1000);
function writeList() {
$("#learning-here").text(value);
}
console.log(value);
});
如何在 span 上一一显示数组元素? 我在上面的两次尝试中做错了什么?
谢谢。
最佳答案
setTimeout
函数可能不是这里的最佳选择。我认为你应该使用函数setInterval
,它以一定的间隔运行特定的回调/函数,直到间隔被清除。
let learning = [
"HTML",
"CSS",
"JavaScript",
"JQuery",
"Git",
"GitHub",
"Bootstrap",
"Sass",
"JSon"
];
// the index to show
let currentIndex = 0;
let learningElement = document.getElementById('learning-here');
// we create an interval variable to clear it later,
// we are also using an arrow function to have access to variable outside the function's scope.
let interval = setInterval(() => {
// we show the string at the current index and then increment the index.
learningElement.innerHTML = learning[currentIndex++];
// if the index if bigger than the length of our array, we've shown every element in the array.
if(currentIndex >= learning.length) {
// we clear the interval so it stops.
clearInterval(interval);
// alternativaly, we could start over by setting the current index back to 0
//currentIndex = 0;
}
}, 1000);
<div id="learning-here"></div>
因为你说你的 Jquery 知识有限,所以我选择使用纯 Javascript。
关于javascript - 如何在 HTML 元素中显示和隐藏数组的每个项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58838110/