【发布时间】:2020-05-23 21:50:13
【问题描述】:
我正在尝试将 JavaScript 类架构与 addEventListener 结合使用,这样我就可以一次定义一系列类方法,这些方法将应用于所有适当的 HTML 和/或 CSS 对象。下面是一个只有一个圆圈的示例,单击时应切换红色或蓝色。不幸的是,类确实架构无法与 DOM 正确通信。
我选择内联编写脚本只是为了更轻松地探索基本概念,而不是为了问题的凝聚力而在多个文件中杂耍(我确实意识到,实际上,我可能会使用单独的 HTML 和 JS文件。)
我想按原样进行编码,以便在单击时使圆圈改变颜色。 (另外,没有使用类架构时的代码DID功能。如果有用我可以补充。)
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.circle {
height: 50px;
width: 50px;
background-color: #555;
border-radius: 50%;
}
</style>
</head>
<body>
<h2>Circle CSS</h2>
<div class="circle"></div>
<script>
class GameObject{
constructor(shape){
this.shape = shape;
this.clicks = 0;
};
clickEvent(){
this.shape.addEventListener('click',function(){
this.clicks += 1
if (this.clicks % 2 == 1){
this.shape.style.backgroundColor = 'red';
}else{
this.shape.style.backgroundColor = 'blue';
}
})
};
};
let shape = document.querySelector('.circle')
let s = new GameObject(shape);
console.log(s);
</script>
</body>
</html>
此外,以下问题/答案在我脑海中浮现,尽管它们是相关的: Javascript Class & EventListener Dealing with Scope in Object methods containing 'this' keyword called by Event Listeners
编辑:我听取了评论的建议并将clickEvent() 添加到此构造函数中。但是,触发了以下错误:
Uncaught TypeError: Cannot read property 'style' of undefined
at HTMLDivElement.<anonymous> (circle.html:31)
【问题讨论】:
-
你永远不会调用 clickEvent 方法,所以事件监听器永远不会触发。尝试在构造函数中调用该方法。
-
this不是s的GameObject实例;它是元素。见stackoverflow.com/questions/20279484/…
标签: javascript class dom-events