带有 boolean 值的 JavaScript if 语句

标签 javascript html if-statement boolean

我正在尝试创建一个按钮来显示或隐藏我的 div 元素,以便使用同一按钮打开和关闭它。我不明白为什么它不起作用,当我单击按钮时没有任何反应,有人可以帮助我吗?

<!DOCTYPE html>
<html>
<head>
<style> 
#myDIV {
    width: 500px;
    height: 500px;
    background-color: lightblue;
    display: none;
}
</style>
</head>
<body>

<p>Click the "Try it" button to set the display property of the DIV element:</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

<p><b>Note:</b> The element will not take up any space when the display property set to "none".</p>

<script>

var div_aperto = false;

function myFunction(div_aperto) 

   if (div_aperto) { 
       div_aperto = false;
       document.getElementById("myDIV").style.display = "none"; }   
   
   else { div_aperto = true;
       document.getElementById("myDIV").style.display = "block"; } 
      
</script>

</body>
</html>

最佳答案

函数语句没有括号,也不需要参数

function myFunction() {

   if (div_aperto) { 
       div_aperto = false;
       document.getElementById("myDIV").style.display = "none"; }   

   else { div_aperto = true;
       document.getElementById("myDIV").style.display = "block"; } 
}

关于带有 boolean 值的 JavaScript if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48624029/

相关文章:

javascript - 如何禁用默认键盘?我只想在我的网页中显示自定义键盘

javascript - 如果时间结束如何发出警报

javascript - Html 选择选项 onclick 在 Chrome 中不起作用,可能是另一个

java - 如何过滤 JSoup 中嵌套标签中的噪音? java

c - 检查文件内容的程序。有没有更好的办法?

java - 搜索方法帮助,

javascript - 访问 HTML 文件中的 Javascript 变量

javascript - 将 Ajax 页面保存到磁盘时出现差异

jquery - 如何在窗口大小调整时自动调整字体和图像(完整网站)的大小?

jquery - JavaScript 的 IF 语句