使用Javascript我试图获取一串文本并将其分解为单个单词,然后将它们连续显示以设置延迟分隔。我已经看过其他'for loop in for loop'堆栈溢出答案,但无法弄明白。下面的代码正确地将字符串分隔成一个单词数组,但然后循环显示最后一个单词而没有延迟。
var string = "Display this line of text as individual words in two second intervals!";
var delay = 2000;
function myFunction() {
var array = string.split(' ');
for (var i = 0; i < array.length; i++) {
setTimeout(function() {
document.getElementById("textbox").innerHTML = array[i];
}, delay);
}
}
<button onclick="myFunction()">Run</button>
<div id="textbox"></div>
答案 0 :(得分:4)
你应该使用闭包。另外,请查看数据如何传递到innerHTML
。
var string = "Display this line of text as individual words in two second intervals!";
var delay = 2000;
function myFunction() {
var array = string.split(' ');
for (var i = 0; i < array.length; i++) {
(function (str) {
setTimeout(function () {
document.getElementById("textbox").innerHTML = str;
}, delay * i);
})(array[i]);
}
}
&#13;
<button onclick="myFunction()">Run</button>
<div id="textbox"></div>
&#13;
答案 1 :(得分:0)
您可以使用Symbol.iterator
let str = "Display this line of text as individual words in two second intervals";
str = str.split(' ');
let count = str.length;
let string = str[Symbol.iterator]();
let interval = setInterval(function() {
count--;
let div = document.createElement('div');
div.innerText = string.next().value;
document.body.appendChild(div);
if (count === 0) {
clearInterval(interval)
}
}, 500);