<!doctype html>
<html lang='en'>
<head>
<title>闭包示例</title>
<style>
.table-normal {
width: 80%;
border: 1px solid #ccc;
border-collapse: collapse;
}
.table-normal th,
.table-normal td {
padding: 8px;
border: 1px solid #ccc;
text-align: left;
}
.outBox .checkbox {
width: 20px;
height: 20px;
border: 1px solid #ccc;
display: inline-block;
margin-right: 10px;
cursor: pointer;
}
.outBox .checkbox.ok {
background: url('./images/apply_check_ok_yes_128px_2293_easyicon.net.png') center center no-repeat;
background-size: 80%;
}
.outBox .checkbox.no {
background: url('./images/close_802px_1161619_easyicon.net.png') center center no-repeat;
background-size: 80%;
}
</style>
</head>
<!-- https://www.easyicon.net -->
<!-- 作业要求: -->
<!-- 1. 尽量用原生的方式,
2. 不用要let块级作用域 -->
<!-- 提示:我在每个checkbox都加了一个ok样式名, 代表打钩 ,
no代表打叉, 供参考,上面样式 -->
<!-- 作业需求 -->
<!-- 1. 点击每个checkbox, 第一次是打勾, 第二次打叉 , 第三次恢复原来的不选状态
2. 每个checkbox的状态不能相互受影响
3. 点击发送按钮,把获取到的状态 以数组的形式 打印出来 -->
<body>
<div class="outBox">
<table class="table-normal">
<tr>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>状态</th>
</tr>
<tr>
<td>小明</td>
<td>男</td>
<td>10</td>
<td><span class="checkbox"></span></td>
</tr>
<tr>
<td>小刚</td>
<td>男</td>
<td>10</td>
<td><span class="checkbox"></span></td>
</tr>
<tr>
<td>小红</td>
<td>男</td>
<td>10</td>
<td><span class="checkbox"></span></td>
</tr>
<tr>
<td>小沙</td>
<td>男</td>
<td>10</td>
<td><span class="checkbox"></span></td>
</tr>
<tr>
<td>小杨</td>
<td>男</td>
<td>10</td>
<td><span class="checkbox"></span></td>
</tr>
<tr>
<td>小松</td>
<td>男</td>
<td>10</td>
<td><span class="checkbox"></span></td>
</tr>
</table>
<!-- <span class="checkbox"></span>
<span class="checkbox"></span>
<span class="checkbox"></span>
<span class="checkbox"></span> -->
</div>
<button type="button" id="btnSend">发送</button>
<script>
for (var checkboxSpan of document.querySelectorAll('.outBox>.table-normal .checkbox')) {
// debugger;
console.log(checkboxSpan);
(function (checkboxElement) {
var clickCounter = 0,
maxState = 3;
checkboxElement.onclick = function (e) {
clickCounter++;
clickCounter = clickCounter % maxState;
// debugger;
switch (clickCounter) {
case 0:
e.target.classList.remove('ok')
e.target.classList.remove('no');
break;
case 1:
e.target.classList.add('ok')
e.target.classList.remove('no');
break;
case 2:
e.target.classList.remove('ok')
e.target.classList.add('no');
break;
default:
break;
}
}
})(checkboxSpan);
}
document.getElementById('btnSend').onclick = function (e) {
var states = [];
var statesForString = [];
var stateDictionary = {
0: "normal",
1: "ok",
2: "no"
};
for (var checkboxSpan of document.querySelectorAll('.outBox>.table-normal .checkbox')) {
var state = 0;
if (checkboxSpan.classList.contains('ok')) {
state = 1;
} else if (checkboxSpan.classList.contains('no')) {
state = 2;
}
states.push(state);
statesForString.push(stateDictionary[state]);
}
console.log("当前状态: ", states, statesForString);
}
</script>
</body>
</html>
网友评论