老师我这样写对吗?

来源:3-13 编程练习

DB1时间的玫瑰

2021-08-19 10:29:53

<!DOCTYPE html>

<html>


<head>

    <meta charset="utf-8">

    <title>Document</title>

    <style>

        div {

            width300px;

            margin20px 0;

            line-height30px;

            background: yellowgreen;

        }

    </style>

</head>


<body>

    <button id="start">开始</button>

    <button id="stop">停止</button>

    <div id="box"></div>

    <script>

        const startBtn = document.getElementById('start')

        const stopBtn = document.getElementById('stop')

        const box = document.getElementById('box')

        let timer;

        var show = {

                content: "Hello World",

                timer: null,

                start: function() {

                    // 在此补充代码

                    startBtn.addEventListener('click', () => {

                        timer = setInterval(() => {

                            box.innerText += this.content;

                        }, 1000)

                    }, false);

                },

                stop: function() {

                    // 在此补充代码

                    stopBtn.addEventListener('click', () => {

                        clearInterval(timer);

                    }, false);

                },

            }

            // 在此补充代码

        show.start();

        show.stop();

    </script>

</body>


</html>


写回答

1回答

好帮手慕星星

2021-08-19

同学你好,代码问题如下:

1、timer属性在show对象中有定义,用的时候需要通过this获取,如果直接用timer相当于重新声明了变量,建议改为this.timer

2、多次点击start按钮,定时器会叠加,导致添加内容时间加快,建议在点击的时候先去掉前面的定时器

3、内容前后没有空格

http://img.mukewang.com/climg/611dc8320934a1b703750105.jpg

建议拼接的时候手动添加空格。

参考修改:

http://img.mukewang.com/climg/611dc8c609fe780b06640306.jpg

http://img.mukewang.com/climg/611dc8ee09e43aa905670318.jpg

祝学习愉快!

0

0 学习 · 15276 问题

查看课程