当将一个字符串添加到 span 标签时,循环只会显示数组中的最后一个字符串。

7

我希望每1.5秒更换span标签中的单词,但目前只显示数组“list”中的最后一个单词。

这是我的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 调用之间没有暂停。 - Patrick Evans
你不需要一个循环...它会在每个间隔触发时运行。所以同样的循环每次都会产生相同的结果. - charlietfl
但是当我删除setInterval并只使用for循环时,它做的事情是一样的。 - Jake123
5个回答

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
<span id="word"></span>

如果您不想使用 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);
<span id="word"></span>

补充说明:相反的方法是使用list.unshift(list.pop()),您可以在这里看到。

就性能而言,使用counter的解决方案应该更快,但由于您的数组很小,所以差异不应引起任何担忧。


谢谢,这正是我在寻找的! - Jake123
@Jake123 如果你感兴趣的话,我还添加了一种使用数组操作来完成它的(正确)方法 - 而不是使用 counter。不客气。祝你编程愉快。 - Roko C. Buljan
好的,谢谢你提供这个信息。还有一个问题,有办法让每个单词都淡入吗? - Jake123
@Jake123 当然可以,你可以从元素中切换一个类...使用jQuery的更好方法可以在这里找到:https://dev59.com/IGIj5IYBdhLWcg3wCxB0 - Roko C. Buljan

0
你可以尝试这个。不是循环,只是每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>


0

最好使用setTimeout。每个迭代都应该有自己的超时时间。另请参阅

(() => {
  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);
  }
})();
<div id="words"></div>


0
我会使用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);
<span id="word"></span>


-1
你的代码问题在于每次调用间隔函数时,循环都会被执行并打印元素,因为你在每次迭代时都替换了整个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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接