javascript - 循环仅在添加 span 标记时显示数组中的最后一个字符串

标签 javascript html arrays loops for-loop

我想每 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>

最佳答案

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

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>

如果您不想使用计数器,而是使用数组操作:

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>

P.S: 如您所见here,逆将使用list.unshift(list.pop()) .

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

关于javascript - 循环仅在添加 span 标记时显示数组中的最后一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42596076/

相关文章:

javascript - 在不知道唯一 ID 的情况下如何获取特定的 firebase 数据?

jquery - Bootstrap 4 模态 - 单击按钮但模态不显示

javascript - 如何将 HTML 字符串呈现为真正的 HTML?

java - 将 int 从 .txt 传输到数组的更有效方法

javascript - .on eventlistener 适用于 firefox 但不适用于 IE 或 chrome

javascript - jQuery .click 问题

javascript - 抓取网页没有进行 ajax 调用但数据不在 DOM 中

html - 使用 "left"作为移动的 CSS 关键帧动画在 Internet Explorer 中不起作用

python - 如何在 python 中找到二维数组的临界点?

c# - 索引超出数组范围 C#