首页 > 解决方案 > Javascript 代码在第二次点击 html 按钮之前不会触发?

问题描述

我正在学习 javascript,而这段简单的代码无法按我需要的方式工作。

我只需要单击按钮即可显示主标签。但是,它不想显示,直到第二次单击。

所以第一次点击不显示主要。第二次点击就可以了。

我尝试在 html 文档周围移动我的编码(在正文结束标记之前/之后等)。

我已经查看了堆栈溢出,类似的问题并没有真正帮助我的情况。或者至少我不明白他们如何帮助我作为初学者。

var aboutShow = document.getElementById("aboutLink");
aboutShow.addEventListener("click", displayMain);

function displayMain(){
  var mainSection = document.getElementsByTagName("main")[0];
  if (mainSection.style.display === "none"){
    mainSection.style.display = "grid";
  }
  else{
    mainSection.style.display = "none";
  }
}
main{display:none;}
<main> ... </main>
<button type="button" id="aboutLink">About</button>

我必须缺少一些东西来阻止第一次点击触发代码。我的意思是,这似乎很简单???

标签: javascripthtmlcssdomevent-listener

解决方案


if (mainSection.style.display === "none")正在寻找一个内联样式标签,所以不要display:none;在你的 CSS 中设置,只需在元素上设置它内联:

var aboutShow = document.getElementById("aboutLink");
aboutShow.addEventListener("click", displayMain);

function displayMain(){
  var mainSection = document.getElementsByTagName("main")[0];
  if (mainSection.style.display === "none"){
    mainSection.style.display = "grid";
  }
  else{
    mainSection.style.display = "none";
  }
}
<main style="display:none;"> ... </main>
<button type="button" id="aboutLink">About</button>


推荐阅读