首页 > 解决方案 > 在类中向元素添加事件侦听器时出错

问题描述

当我运行代码时,我收到一条错误消息:未捕获的 TypeError:this.startButton.addEventlistener 不是我不知道如何修复的函数。

我可以 console.log 类内的按钮,但不能添加奇怪的事件监听器

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <input id="duration" />
    <button id="start">Start</button>
    <button id="pause">Pause</button>


    <script src="index.js"></script>

</body>
</html>

JS:

class Timer{
    constructor(durationInput, startButton, pauseButton){
        this.durationInput = durationInput;
        this.startButton = startButton;
        this.pauseButton = pauseButton;


        this.startButton.addEventlistener('click',this.start)

    }


    start(){
        console.log("time to start the timer")
    }

}

const durationInput = document.querySelector('duration');
const startButton = document.querySelector('#start');
const pauseButton = document.querySelector('#pause');

const timer = new Timer(durationInput, startButton, pauseButton)

标签: javascripthtml

解决方案


你只是有一个错字,它是this.startButton.addEventListener('click',this.start)L 大写。


推荐阅读