javascript - 想要使用布尔值显示和隐藏元素 true false
问题描述
我有 Div Container,我想通过单击按钮来显示和隐藏它。但我想使用 **Boolean True false 值
function myFunction() {
let booleanValue = true;
var x = document.getElementById("myDIV");
if (booleanValue === true) {
x.style.display = "block";
booleanValue = false;
} else {
x.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
display:none;
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
e**。
解决方案
尝试使用全局变量。let booleanValue = true;
与其在内部定义,不如myFunction
在函数外部将其定义为全局变量。这样每次函数执行时,您都可以切换变量的值。
var booleanValue = true;
function myFunction() {
booleanValue = !booleanValue;
var x = document.getElementById("myDIV");
if (booleanValue === true) {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
#myDIV {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<button onclick="myFunction()">Toggle Div</button>
<div id="myDIV">
This is my DIV element.
</div>
推荐阅读
- azure - 具有不同标题的文件以复制 azure dwh 表中的数据
- ruby-on-rails - 在设计注册表单中使用参数
- php - 如何在 android 中使用 MySql 服务器(在桌面上下载)?
- java - getYesterdayDate_yyyy_MM_dd() 这个方法返回类型为 java.sql.date
- python - 为什么这个 tkinter 登录窗口不起作用?
- sql - 如何使用 sql 选择查询通过动态字段名称更新值
- julia - 使用 Plotly Julia 的下拉选择
- java - 从后台删除应用程序时也没有获取位置更新
- stored-procedures - 当我的存储过程出错时如何设置参数?
- android - 如何获取窗口(如对话框、弹出菜单...)