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