代码之家  ›  专栏  ›  技术社区  ›  Ezeeroc

div元素未更改其文本内容

  •  0
  • Ezeeroc  · 技术社区  · 7 年前

    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);
    

    我肯定这很容易,但我想不出来。非常感谢。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mamun    7 年前

    因为你没有提供问题的细节 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>