成品预览
需求:
- 动态显示当前时间;
- 随机点名;
实现步骤:
- 1. ajax异步加载获取名单;
- 2. 循环添加名字到页面;
- 3. 设置两个循环定时器,一个实现实时显示当前时间;另一个设置为“点击点名”按钮的点击事件,将时间间隔设置较短,利用随机数+取余来定位名字;
- 4. 设置“点击停止”按钮的点击事件,禁用“点击点名”按钮,停止计时器
实现代码
<!DOCTYPE html>
<head>
<title>简易点名系统</title>
<meta charset="utf-8"/>
<style type="text/css">
body {
background-color: gray;
}
table > div {
width: 60px;
height: 30px;
margin: 10px;
background-color: lightblue;
border: #000 1px solid;
font-size: 14px;
float: left;
text-align: center;
line-height: 20px;
}
input {
width: 90px;
height: 30px;
margin: 10px;
background-color: antiquewhite;
border: #000 1px solid;
}
</style>
//引入JQuery
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
</head>
<body>
<h3 align="center">简易<font color="red"></font>点名系统</h3>
<div align="center"><span id="span_span"></span></div>
<table id="div1" align="center">
</table>
<table align="center">
<tr>
<td>
<input id="input01" type="button" value="点击点名" onclick="checkName()"/>
<input type="button" value="点击停止" onclick="stop()"/>
</td>
</tr>
</table>
<script type="text/javascript">
$(function () {
$.get({
url: "json/names.json",
success: function (data) {
$.each(data, function (i, name) {
$("#div1").append(`<div id="span${i}">${name}</div>`);
if (i > 4 && i % 5 === 0) {
$("#div1").append(`</br>`);
}
});
},
dataType: "json"
});
});
$("#span_span").html(new Date().toLocaleString());
$(function () {
setInterval(function () {
let str = new Date().toLocaleString();
$("#span_span").html(str);
}, 1000);
});
let num = Math.round(Math.random() * 100) % 27;
let flag = 1;
function checkName() {
flag = setInterval(function () {
$("#span" + num).attr("style", "background-color: lightblue");
num = Math.round(Math.random() * 100) % 27;
$("#span" + num).attr("style", "background-color: red");
$("#input01").prop("disabled", true);
}, 100);
}
function stop() {
clearInterval(flag);
$("#input01").prop("disabled", false);
}
</script>
</body>
</html>