在css文件中是一些文本,我想动态更改div
元素的文本内容(首先显示第一个文本,然后是第二个等),问题是即使我看到了console.log(message[i].text)
有文字(即"Insert the FIRST text you want."
等),document.getElementById("background").innerHTML = message[i].text;
仍为空。
这是css文件:
const message = [
{
"text":"Insert the FIRST text you want."
},
{
"text":"Insert the SECOND text you want."
},
{
"text":"Insert the THIRD text you want."
},
{
"text":"Insert the FOURTH text you want."
},
{
"text":"Insert the FIFTH text you want."
},
{
"text":"Insert the SIXTH text you want."
},
{
"text":"Insert the SEVENTH text you want."
},
{
"text":"Insert the EIGHTH text you want w this is just to test the words w ww www."
}
]
这是js函数:
function insertText(a, b){
(function theLoop (i) {
setTimeout(function () {
document.getElementById("background").innerHTML = message[i].text;
if (i++ < b-1) {
theLoop(i);
}
else {
i = a;
//theLoop(i);
}
}, delayValue);
})(a, b);
}
这就是我所说的:
var l = message.length;
insertText(0, l);
我确定这很容易,但我无法弄明白。非常感谢。
答案 0 :(得分:2)
由于您没有提供问题的详细信息,例如HTML
,您收到的错误(如果有),很难回答这个问题。
虽然我可以通过添加一个HTML
元素并在delayValue
中设置setTimeout()
的值来开始使用您的代码。
尝试以下方法:
const message = [
{
"text":"Insert the FIRST text you want."
},
{
"text":"Insert the SECOND text you want."
},
{
"text":"Insert the THIRD text you want."
},
{
"text":"Insert the FOURTH text you want."
},
{
"text":"Insert the FIFTH text you want."
},
{
"text":"Insert the SIXTH text you want."
},
{
"text":"Insert the SEVENTH text you want."
},
{
"text":"Insert the EIGHTH text you want w this is just to test the words w ww www."
}
]
function insertText(a, b){
(function theLoop (i) {
var delayValue = 1000;
setTimeout(function () {
document.getElementById("background").innerHTML = message[i].text;
if (i++ < b-1) {
theLoop(i);
}
else {
i = a;
//theLoop(i);
}
}, delayValue);
})(a, b);
}
var l = message.length;
insertText(0, l);
<div id="background"></div>