简体   繁体   English

在 class 内向元素添加事件侦听器时出错

[英]Error when adding event listener to element when inside a class

When I run the code I get an error that says: Uncaught TypeError: this.startButton.addEventlistener is not a function which I do not know how to fix.当我运行代码时,我收到一条错误消息: Uncaught TypeError: this.startButton.addEventlistener is not a function 我不知道如何修复。

I can console.log the button inside the class but cannot add the event listener which is weird我可以控制台记录 class 内的按钮,但无法添加奇怪的事件侦听器

HTML: 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: 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)

You just have a typo it's this.startButton.addEventListener('click',this.start) the L goes in uppercase.你只是有一个错字this.startButton.addEventListener('click',this.start) L 大写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM