我正在学习 javascript,这段简单的代码无法按我需要的方式运行。
我所需要的只是在单击按钮时显示主标记。但是,在第二次点击之前它不会显示。
所以第一次点击不显示主要。第二次点击。
我试过在 html 文档中移动我的代码(在 body 结束标记之前/之后,等等)。
我查看了堆栈溢出,类似的问题对我的情况没有真正帮助。或者至少我不明白他们如何帮助我这个初学者。
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")
正在寻找一个内联样式标签,所以不要在你的 CSS 中设置 display:none;
, 只需在元素上将其设置为内联:
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>
关于Javascript 代码直到第二次点击 html 按钮才会触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57061351/