javascript - 如何在 HTML 元素中显示和隐藏数组的每个项目?

标签 javascript jquery html arrays

我有这个数组:

   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/

相关文章:

javascript - 使用 javascript 打开网页时单击图像链接

javascript - 如何为这个 jQuery 代码定义 if 语句?

javascript - 复制时的 JQuery DatePicker 日期格式问题

Javascript - 删除紧跟换行符的空格

javascript - 如何获取特定div上的滚动方向

javascript - 使用 sammy.js 重新加载页面

javascript:选择随机项目(只要它尚未显示)

javascript - jquery 在没有硬编码的情况下显示/隐藏 div 中的内容

javascript - 如何从 DOM 获取元素并设置 onclick 事件?

html - Angular 2 中的字符串最佳实践