简体   繁体   中英

How Can I? Set foo.style.display where foo is the element name based on a js variable rising in increments

I have my program set up so that it autogenerates HTMl and places it into the webpage. Each introduction of new HTMl is given a new ID following along which increment it is at eg <div id = "genQuestion0"> <div id = "genQuestion1"> etc.

The inital div's have all been set through CSS as no display

[id^="genQuestion"]{
    text-align: center;
    display: none;
} 

The first question id = genQuestion0 has been set that upon generation its display is set to block .

How can I make it so that when a button is pressed the previous questions display is changed to none and the next one is set to block .

This is what I have currently for my function but it does not work.

var countclicks = 0;

const nextQuestion = () =>{
  var elementName = `genQuestion${countclicks}`;
  var elementNameNeg = `genQuestion${(countclicks - 1)}`;
  elementName.style.display = "block";
  elementNameNeg.style.display = "none";
  countClicks ++;

}

It's because your is just string and not DOM element.

You can access that element by using document.getElementById(elementNameNeg).style.display = 'block';

So change to this?

var countclicks = 0;
const nextQuestion = () =>{
  var elementName = `genQuestion${countclicks}`;
  var elementNameNeg = `genQuestion${(countclicks - 1)}`;
  document.getElementById(elementName).style.display = "block";
  document.getElementById(elementNameNeg).style.display = "none";
  countClicks ++;

}

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