Как передать HTML-элемент из одного метода в другой в прототипе - PullRequest
0 голосов
/ 28 мая 2019

Как передать результат из метода 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.log(this.playerElementChoice());
}

}

При попытке вызвать метод playerElementChoice () в методе startGame () я получаю сообщение об ошибке: Не удается прочитать свойство 'className' из неопределенного в Game.playerElementChoice (Game.js: 17) в Game.startGame (Game.js: 28).

Что я делаю не так?

1 Ответ

0 голосов
/ 28 мая 2019

Если вы хотите выбрать одну опцию в списке и зарегистрировать выбранное значение 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.log(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>

Надеюсь, это поможет

...