javascript - 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>
我必须缺少一些东西来阻止第一次点击触发代码。我的意思是,这似乎很简单???
解决方案
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>
推荐阅读
- python - Applying pandas map without function
- reactjs - 在handleIncrement 方法中,“this”指的是未定义
- python - 在文档中搜索特定字符串,然后打印出该字符串的一部分
- permissions - Google Dirve:转移所有权并保存到特定文件夹
- java - Android Studio中的绿色和红色表示什么有人可以解决吗?
- dataweave - 如何在 Mule 中为 Excel 列设置自动调整
- c# - 如何使物体在Unity中从随机方向直线移动
- javascript - 按特定键和总和聚合对象数组
- r - 用传单绘制世界 chloropeth 地图
- node.js - 如何保持 GCS 密钥 json 文件安全?