请老师检查作业

来源:3-13 编程练习

鱼档卖鱼

2022-05-17 17:39:19

<!DOCTYPE html>

<html lang="en">


<head>

    <meta charset="UTF-8">

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

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

        // 方法一:更改this指向

        // var show = {

        //     content: "Hello World ",

        //     timer: null,

        //     start: function () {

        //         let that = this;

        //         startBtn.onclick = function () {

        //             clearInterval(that.timer);

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

        //                 box.innerHTML += that.content;

        //             }, 1000);

        //         }

        //     },

        //     stop: function () {

        //         let that = this;

        //         stopBtn.onclick = function () {

        //             clearInterval(that.timer)

        //         }

        //     },

        // }

        // show.start();

        // show.stop();

        // 方法二:箭头函数

        var show = {

            content: "Hello World ",

            timer: null,

            start: function () {

                startBtn.onclick = () => {

                    clearInterval(this.timer);

                    this.timer = setInterval(() => {

                        box.innerHTML += this.content;

                    }, 1000);

                }

            },

            stop: function () {


                stopBtn.onclick = () => {

                    clearInterval(this.timer)

                }

            },

        }

        show.start();

        show.stop();

    </script>

</body>


</html>


写回答

1回答

好帮手慕星星

2022-05-17

同学你好,这两种方法都是正确的,很棒!祝学习愉快~

0

0 学习 · 17877 问题

查看课程