老师请检查作业

来源:3-12 箭头函数的应用

qq_慕神8318241

2021-11-27 16:56:15

<!DOCTYPE html>

<html>


<head>

    <meta charset="utf-8">

    <title>Document</title>

    <style>

        div {

            width: 300px;

            margin: 20px 0;

            line-height: 30px;

            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')

        //普通函数实现

        // var show = {

        //     content: "Hello World",

        //     timer: null,

        //     start: function () {

        //         var self = this;

        //         console.log(this);

        //         startBtn.addEventListener('click', function () {

        //             self.timer = setInterval(function() {

        //                 box.innerHTML = self.content;

        //                 self.content += "Hello World";


        //             }, 2000)

        //         })

        //     },

        //     stop: function () {

        //         var self = this;

        //         stopBtn.addEventListener('click',function(){

        //             clearInterval(self.timer);

        //         })

        //     },

        // }

        // show.start();

        // show.stop();


        //箭头函数实现

        var show = {

            content: "Hello World",

            timer: null,

            start: function () {

                console.log(this);

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

                    this.timer = setInterval(() => {

                        box.innerHTML = this.content;

                        this.content += "Hello World";

                    }, 2000)

                })

            },

            stop: function () {

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

                    clearInterval(this.timer);

                })

            },

        }

        show.start();

        show.stop();

    </script>

</body>


</html>


写回答

1回答

好帮手慕星星

2021-11-27

同学你好,代码逻辑是可以的,但是还可以优化:

1、为了避免多次点击‘开始’按钮,定时器叠加问题,可以在设置定时器前,清除定时器

2、拼接的字符,前面可以手动加空格,这样就不会紧挨着变为一个单词了

参考:

https://img.mukewang.com/climg/61a1fbc2099e8f9606860550.jpg

祝学习愉快!

0
hq_慕神8318241
hp>好的谢谢老师

h021-11-27
共1条回复

0 学习 · 17877 问题

查看课程