简体   繁体   中英

div element not changing its text content

In a css file is some text and I want to change the text content of a div element dynamically (first showing the 1st text, then the 2nd etc.) and the problem is that even though i see that console.log(message[i].text) has the text (ie "Insert the FIRST text you want." etc.), document.getElementById("background").innerHTML = message[i].text; is still empty.

This is the css file:

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."
    }
]

This is the js function:

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

And this is how Im calling it:

var l = message.length; 
insertText(0, l);

Im sure it is something easy, but I cant figure it out. Thanks a lot.

Since you didn't provide details of the question like the HTML , the error you are getting (if any), it is really difficult to answer the question.

Though I was able to get going with your code by adding one HTML element and setting the value for delayValue in setTimeout() .

Try the following:

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM