Javascript 从onmouseover调用类方法
问题: 我试图从onmouseover事件调用一个类方法。显然我不知道我在做什么 预期结果: 结果: 代码:Javascript 从onmouseover调用类方法,javascript,Javascript,问题: 我试图从onmouseover事件调用一个类方法。显然我不知道我在做什么 预期结果: 结果: 代码: 谢谢你的帮助。你非常接近。您只是错过了使用事件侦听器 method1() { console.log('method1 says, this.cssId = ' + this.cssId); var appEl = document.getElementById(this.cssId); ap
谢谢你的帮助。你非常接近。您只是错过了使用事件侦听器
method1() {
console.log('method1 says, this.cssId = ' + this.cssId);
var appEl = document.getElementById(this.cssId);
appEl.addEventListener('mouseover', this.method2) = this.method2;
}
是的,但是有一个更合适的,标准的欺骗目标。。。它在哪里…这能回答你的问题吗?
constructor says, this.cssId = app
method1 says, this.cssId = app
method2 says, this.cssId = undefined
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8'>
<title>Test</title>
<style>
#app{
border: 5px solid orange;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id='app'>Test</div>
<script>
class MyClass {
// Fields
cssId = 'app'
constructor() {
console.log('constructor says, this.cssId = ' + this.cssId);
}
// Methods
method2() {
console.log('method2 says, this.cssId = ' + this.cssId);
var appEl = document.getElementById(this.cssId);
}
method1() {
console.log('method1 says, this.cssId = ' + this.cssId);
var appEl = document.getElementById(this.cssId);
appEl.onmouseover = this.method2;
}
}
let thing = new MyClass();
thing.method1();
</script>
</body>
</html>
method1() {
console.log('method1 says, this.cssId = ' + this.cssId);
var appEl = document.getElementById(this.cssId);
appEl.addEventListener('mouseover', this.method2) = this.method2;
}