使用父级onclick事件显示和隐藏隐藏的div

时间:2017-09-13 17:41:07

标签: javascript html dom

我正在尝试创建一个新闻稿缩略图列表,这些缩略图将显示并隐藏它的父标题的onclick事件。正确调用该函数以显示列表,但不会在第二次单击时再次隐藏它。我确信这很简单,我很想念,但我不知所措。

function showBabList() {
  if (document.getElementById('bablist').style.display = "none") {
    document.getElementById('bablist').style.display = "block";
  } else {
    document.getElementById('bablist').style.display = "none";
  }
}
<h2 onclick="showBabList()">BITSandBYTES Newsletters</h2>
<div id="bablist" style="display: none;">
  <ul>
    <a href="newsletter/BITSandBYTES2017-07.pdf" target="bab"><img src="images/thumbs/BITSandBYTES2017-07_thumb.png" class="babthumb" height="100px" width="75px"></a>
    <a href="newsletter/BITSandBYTES2017-08.pdf" target="bab"><img src="images/thumbs/BITSandBYTES2017-08_thumb.png" class="babthumb" height="100px" width="75px"></a>
  </ul>
</div>

1 个答案:

答案 0 :(得分:1)

function showBabList() {
  if (document.getElementById('bablist').style.display == "none") {
    document.getElementById('bablist').style.display = "block";
  } else {
    document.getElementById('bablist').style.display = "none";
  }
}
<h2 onclick="showBabList()">BITSandBYTES Newsletters</h2>
<div id="bablist" style="display: none;">
  <ul>
    <a href="newsletter/BITSandBYTES2017-07.pdf" target="bab"><img src="images/thumbs/BITSandBYTES2017-07_thumb.png" class="babthumb" height="100px" width="75px"></a>
    <a href="newsletter/BITSandBYTES2017-08.pdf" target="bab"><img src="images/thumbs/BITSandBYTES2017-08_thumb.png" class="babthumb" height="100px" width="75px"></a>
  </ul>
</div>

<强> WRONG
if (document.getElementById('bablist').style.display = "none")

<强> CORRECT
if (document.getElementById('bablist').style.display == "none")