Как передать результат из метода playerElementChoice() в startGame()
class Game {
constructor() {
this.options = document.querySelectorAll('.options');
this.options.forEach(item => {
item.addEventListener('click', this.playerElementChoice);
});
document.querySelector('button.start').addEventListener('click', this.startGame.bind(this));
}
playerElementChoice() {
const name = this.firstElementChild.className;
return name;
}
startGame() {
console.info(this.playerElementChoice());
}
}
При попытке вызвать метод playerElementChoice() в методе startGame() получаю ошибку: Не удается прочитать свойство className неопределенного значения в Game.playerElementChoice (Game.js:17) в Game.startGame (Game.js:28).
Что я делаю неправильно ?
если вы хотите выбрать один параметр в списке и зарегистрировать выбранное значение li className, вы должны изменить свой код, добавив некоторую привязку:
class Game {
constructor() {
this.options = Array.from(document.getElementById('options').children);
this.startButton = document.querySelector('button.start');
this.name = '';
this.playerElementChoice = this.playerElementChoice.bind(this);
this.startGame = this.startGame.bind(this)
}
init() {
this.options.forEach(item => {
item.addEventListener('click', this.playerElementChoice)
});
this.startButton.addEventListener('click', this.startGame);
}
playerElementChoice(e) {
e.preventDefault();
this.name = e.target.className;
}
startGame() {
console.info(this.name);
}
}
let game = new Game()
game.init()
<button class = "start">start</button>
<ul id = "options">
<li class = "option1" name = "one">1</li>
<li class = "option2" name = "two">2</li>
<li class = "option3" name = "three">3</li>
</ul>
Надеюсь, поможет
playerElementChoice
требуетthis
контекста элемента с дочерним элементом, но вconsole.info(this.playerElementChoice());
вы вызываете его с контекстом экземпляра Game