如何将HTML元素从原型中的一种方法传递到另一种方法

时间:2019-05-27 21:44:03

标签: javascript oop es6-class

如何将结果从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());
}

}

尝试在方法startGame()中调用方法playerElementChoice()时出现错误: 无法从Game.startGame(Game.js:28)的Game.playerElementChoice(Game.js:17)读取未定义的属性“ className”。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

如果要在列表中选择单个选项并记录所选的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>

希望有帮助