【问题标题】:Loop is only displaying the last string in an array when adding it a span tag循环仅在添加跨度标记时显示数组中的最后一个字符串
【发布时间】:2017-07-24 13:53:15
【问题描述】:

我想每 1.5 秒更改一次 span 标记中的单词,但到目前为止它只是显示数组“列表”中的最后一个单词。

这是我的 javascript

var list = [
    "websites",
    "user interfaces"
];


setInterval(function() {
for(var count = 0; count < list.length; count++) {
    document.getElementById("word").innerHTML = list[count];
}}, 1500);

这里是html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <span id="word"></span>
</body>
</html>

【问题讨论】:

  • 因为您在单个 setInterval 调用中运行完整的 for 循环。 for 循环不会在 setInterval 调用之间暂停
  • 你不想要一个循环......每次触发间隔时它都会运行。所以每次运行相同的循环都会产生相同的结果
  • 但是当我删除 setInterval 并且只使用 for 循环时,它会做同样的事情..

标签: javascript html arrays loops for-loop


【解决方案1】:

你可能想试试这个。不循环,只是每 1.5 秒调用一次changeWord 函数。

    var list = [
        "websites",
        "user interfaces"
    ];
    var count = 0;

    function changeWord() {
        document.getElementById("word").innerHTML = list[count];
        count = count < list.length-1 ? count+1 : 0;
    }

    setInterval(function() { changeWord(); }, 1500);
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <span id="word"></span>
</body>
</html>

【讨论】:

    【解决方案2】:

    您不需要 for 循环,只需使用 setInterval、您的 counter 或使用数组操作更简单:

    var list = [
      "websites",
      "user interfaces",
      "cool neh?"
    ];
    
    var count = 0; // Separate your count
    
    function changeWord() { // Separate your concerns
      document.getElementById("word").innerHTML = list[count];
      count = ++count % list.length; // Increment and loop counter
    }
    
    changeWord();                  // First run,
    setInterval(changeWord, 1500); // Subsequent loops
    &lt;span id="word"&gt;&lt;/span&gt;

    如果您不想使用counter,而是使用数组操作

    var list = [
      "websites",
      "user interfaces",
      "cool neh?"
    ];
    
    var ELWord = document.getElementById("word"); // Cache elements you use often
    
    
    function changeWord() {
      ELWord.innerHTML = list[0]; // Use always the first key.
      list.push(list.shift());    // Push the first key to the end of list. 
    }
    
    changeWord();                 
    setInterval(changeWord, 1500);
    &lt;span id="word"&gt;&lt;/span&gt;

    P.S:反之则使用list.unshift(list.pop()),如您所见here

    在性能方面,使用 counter 的解决方案应该更快,但您的 Array 很小,因此差异不会引起任何问题。

    【讨论】:

    • 谢谢,这就是我要找的!
    • @Jake123 如果您有兴趣,我还添加了一种(正确的)方法来使用数组操作 - 而不是使用 counter。不客气。快乐编码
    • 好的,谢谢你,还有一个问题,有没有办法让每个单词淡入?
    • @Jake123 当然,你可以从你的元素中切换一个类...可以在这里找到使用 jQuery 的更好方法:stackoverflow.com/questions/20695877/…
    【解决方案3】:

    最好使用setTimeout。每次迭代都应该有自己的超时时间。 See also

    (() => {
      const words = document.querySelector('#words');
      typeWords([
          "web sites",
          "user interfaces",
          "rare items",
          "other stuff",
          "lizard sites",
          "ftp sites",
          "makebelief sites",
          "fake news sites",
          "et cetera"
      ]);
    
      function typeWords(list) {
        list.push(list.shift()) && (words.innerHTML = list[list.length-1]);
        setTimeout(() => typeWords(list), 1500);
      }
    })();
    &lt;div id="words"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案4】:

      您的代码的问题是,每当调用间隔函数时,都会执行循环并打印元素,因为您在每次迭代时都替换了整个 innerHtml。 如果您想在间隔后一次又一次地打印整个列表元素,可以尝试以下代码。

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <title></title>
      </head>
      <body>
      <span id="word"></span>
      </body>
      

      javascript代码:

        var list = [
      "websites",
      "user interfaces"
      ];
      var count=0;
      function print()
      {
        document.getElementById("word").innerHTML = list[count];
      count += 1;
      count%=list.length;
      }
      setInterval( print(), 1000);
      

      【讨论】:

        【解决方案5】:

        我将通过setTimeout() 完成这项工作,如下所示,

        function loopTextContent(a, el, dur = 1500){
          var  i = -1,
             len = a.length,
            STID = 0,
          looper = _ => (el.textContent = a[i = ++i%len], STID = setTimeout(looper,dur));
          looper();
          return _ => STID;
        }
        
        var list = ["websites", "user interfaces", "user experience", "whatever"],
         getSTID = loopTextContent(list, document.getElementById("word"));
        setTimeout(_ => clearTimeout(getSTID()),10000);
        &lt;span id="word"&gt;&lt;/span&gt;

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-31
          • 2023-03-19
          • 1970-01-01
          • 2012-10-21
          • 1970-01-01
          • 2021-03-03
          相关资源
          最近更新 更多