【问题标题】:Error when adding event listener to element when inside a class在类中向元素添加事件侦听器时出错
【发布时间】:2020-04-23 17:30:57
【问题描述】:

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

我可以控制台记录类中的按钮,但不能添加奇怪的事件监听器

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)

【问题讨论】:

  • 两个错别字:1)(在回答中提到)addEventListener 是函数的名称,2)const durationInput = document.querySelector('duration'); 中的duration 之前缺少#

标签: javascript html


【解决方案1】:

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

【讨论】:

  • 谢谢你我怎么没注意到
猜你喜欢
  • 2020-03-06
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
  • 2010-11-26
相关资源
最近更新 更多