JS小案例_简易点名系统

成品预览

成品预览

需求:
 - 动态显示当前时间;
 - 随机点名;
实现步骤:
 - 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()"/>
            &nbsp;&nbsp;<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");
            //设置点名按钮不可用,防止多次点击出现bug
            $("#input01").prop("disabled", true);
        }, 100);
    }
	//点击停止
    function stop() {
        clearInterval(flag);//清除点名计时器
        $("#input01").prop("disabled", false);//设置点名按钮可用
    }

</script>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值