JavaScript GetElementById当类设置为显示时更改显示无

时间:2022-11-28 16:37:56

When setting a div to display:none using it's ID as the identifier I can then use JavaScript to set display:block and hence have buttons to toggle between divs. However when I use the class as the identifier to set display:none I cannot toggle them to display:block using their unique IDs.

当设置div显示:none使用它的ID作为标识符然后我可以使用JavaScript来设置display:block,因此有按钮在div之间切换。但是,当我使用类作为标识符来设置display:none时,我无法将它们切换为display:block使用它们的唯一ID。

In other words, I want to set a lot of divs to be hidden using their class name, then individually make them visible using their IDs. Is there a reason you can't do that?

换句话说,我想设置很多div使用他们的类名隐藏,然后使用他们的ID单独使它们可见。有没有理由你不能这样做?

1 个解决方案

#1


Is there a reason you can't do that?

有没有理由你不能这样做?

Not that I know

不是我知道的

<p class="blahs" id="blah1">1</p>
<p class="blahs" id="blah2">2</p>
<p class="blahs" id="blah3">3</p>

hideme = document.getElementsByClassName("blahs");
for (var i = 0; i < hideme.length; i++) {
    hideme[i].style.display = "none";
}

showme = document.getElementById("blah1");
showme.style.display = "block";

#1


Is there a reason you can't do that?

有没有理由你不能这样做?

Not that I know

不是我知道的

<p class="blahs" id="blah1">1</p>
<p class="blahs" id="blah2">2</p>
<p class="blahs" id="blah3">3</p>

hideme = document.getElementsByClassName("blahs");
for (var i = 0; i < hideme.length; i++) {
    hideme[i].style.display = "none";
}

showme = document.getElementById("blah1");
showme.style.display = "block";