[英]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.我设置了我的程序,以便它自动生成 HTMl 并将其放入网页中。 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.每次引入新的 HTMl 都会获得一个新的 ID,紧随其后的是增量,例如<div id = "genQuestion0"> <div id = "genQuestion1">
等。
The inital div's have all been set through CSS as no display初始div都通过CSS设置为不显示
[id^="genQuestion"]{
text-align: center;
display: none;
}
The first question id = genQuestion0
has been set that upon generation its display is set to block
.第一个问题id = genQuestion0
已设置为在生成时将其显示设置为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
.我怎样才能做到这样,当按下一个按钮时,前面的问题显示更改为none
,下一个设置为block
。
This is what I have currently for my function but it does not work.这是我目前为我的 function 使用的,但它不起作用。
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.这是因为你只是字符串而不是 DOM 元素。
You can access that element by using document.getElementById(elementNameNeg).style.display = 'block';
您可以使用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 ++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.