博客背景: 由于最近要开发一款电商小程序项目,购物车模块正好要用到这些知识,前来复习一下该功能逻辑。
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
background-color: #ccc;
}
.jdTabContent {
width: 600px;
height: 800px;
margin: 200px auto;
}
.section {
position: relative;
padding: 15px;
border-radius: 10px;
background: #fff;
color: #262626;
margin-top: 10px;
}
.head_wrap {
padding: 15px 10px;
}
.cart-footer {
width: 100%;
height: 60px;
background-color: #fff;
display: flex;
align-items: center;
margin-top: 10px;
border-radius: 10px;
padding-left: 25px;
}
</style>
<body>
<div class="jdTabContent">
<div class="section">
<div class="head_wrap">
<input
class="merchant_checkbox"
type="checkbox"
/>
<span>法德鹿皮旗舰店</span>
</div>
</div>
<div class="section">
<div class="head_wrap">
<input
class="merchant_checkbox"
type="checkbox"
/>
<span>樊者旗舰店</span>
</div>
</div>
<div class="cart-footer">
<input type="checkbox" id="all_select" />
<span>全选</span>
</div>
</div>
<script>
const all_select = document.querySelector('#all_select')
const head_checkbox = document.querySelectorAll('.merchant_checkbox')
// 全选/全不选 父控制子
all_select.addEventListener('click', function () {
for (let i = 0, len = head_checkbox.length; i < len; i++) {
head_checkbox[i].checked = this.checked
}
})
// 方法判断一: 子控制父
for (let i = 0, len = head_checkbox.length; i < len; i++) {
head_checkbox[i].onclick = function () {
// 1: 假设子checkbox已全部选中了
let flag = true
// 2: 修改flag
for (let j = 0, j_len = head_checkbox.length; j < j_len; j++) {
// 只要有一个为不选中flag就不能为true
if (!head_checkbox[j].checked) {
flag = false
}
}
all_select.checked = flag
}
}
// 方法判断二: 子控制父
let count = 0
for (let i = 0, len = head_checkbox.length; i < len; i++) {
head_checkbox[i].onclick = function () {
this.checked ? count++ : count--
all_select.checked = count === head_checkbox.length
}
}
</script>
</body>