【发布时间】:2017-06-08 17:58:55
【问题描述】:
我有一个带有输入类型复选框组的#main-container。这些复选框在选中时会打开按钮列表。
包含所有这些的#main-container 可以通过一个按钮关闭。我遇到的问题是如何使关闭#main-container 的这个按钮也取消选中#main-container 关闭时选中的所有复选框?
在底部,我包含了我目前知道的使用 Javascript 执行此操作的唯一方法,但这意味着为每个复选框创建一个变量,并且该复选框必须具有唯一的 ID。我试图避免这种情况。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>input checkbox</title>
<style>
body {
margin: 0;
background: beige;
border: 1px solid blue;
}
.main-container {
border: 1px solid red;
width: 25%;
position: relative;
}
.toggle-box {
display: none;
}
label {
margin: 0.2em;
display: block;
text-align: center;
transition: all 1s linear;
border: 1px solid green;
}
.toggle-box + div {
display: none;
margin: 0.2em;
text-align: center;
}
.toggle-box:checked + div {
display: block;
border: 1px solid black;
transition: all 1s linear;
}
button {
display: block;
margin: auto;
width: 100%;
}
</style>
</head>
<body>
<div id="main-container" class="main-container">
<label for="toggle-box">A</label>
<input class="toggle-box" id="toggle-box" type="checkbox" >
<div>
<button type="button">submit</button>
<button type="button">submit</button>
</div>
<label for="toggle-box2">B</label>
<input class="toggle-box" id="toggle-box2" type="checkbox" >
<div>
<button type="button">submit</button>
<button type="button">submit</button>
</div>
<div></div>
<div></div>
<div class="test1"></div>
</div>
<button type="button" onclick="closeMe()">close</button>
<button type="button" onclick="openMe()">open</button>
<script>
function closeMe() {
var $toggleBox = document.getElementById("toggle-box");
$toggleBox.checked = false;
document.getElementById("main-container").style.display = "none";
}
function openMe() {
document.getElementById("main-container").style.display = "block";
}
</script>
</body>
</html>
【问题讨论】:
标签: javascript html checkbox input