【发布时间】:2020-12-25 02:49:32
【问题描述】:
我在将值写入 addEventListener 内的变量并将其用作对象属性时遇到问题。关键字 this 显示 Player 对象,但选择属性仍然为空,但在 addEventListener 内一切正常。抱歉我的英语不好,但我真的需要帮助。
export class Player{
constructor(){
this.board = document.querySelector('.playerMoveImg');
this.score = 0;
this.choice = null;
}
moveChoice = () => {
const localChoise = document.addEventListener('click',(event)=>{
if(event.target.value !== undefined){
this.choice = event.target.value;
this.board.style.backgroundImage =`url("src/img/Player${this.choice}.jpg")`;
}
})
console.log(this.choice); //shows null //expect showing event.target.value
}
}
import {Player} from './player.js'
const player = new Player();
player.moveChoice();
【问题讨论】:
-
请始终使用相应的编程语言标签,以吸引更多量身定制的受众,而其他可能对相关技术没有能力的人不会看到您的问题。
标签: javascript scope this addeventlistener