【问题标题】:only one method this.init() works in class [duplicate]this.init() 只有一种方法在类中有效[重复]
【发布时间】:2021-07-20 13:20:24
【问题描述】:

在这里难住了。当我尝试调用 this.makeBoard();它给了我一个类型错误。任何帮助,将不胜感激。我没有包括我的其他方法,但是它们给出了相同的错误。

错误:TypeError:this.makeBoard 不是函数 在 HTMLInputElement

class Game {
  constructor() {
    this.init();
  }

  init() {
    this.board = [];
    this.currPlayer = 1;
    this.button = document.querySelector("#submit");
    this.button.addEventListener('click', function(e){
      e.preventDefault();
      const htmlBoard = document.querySelector('#board');
      this.width = parseInt(document.querySelector('#width'));
      this.height = parseInt(document.querySelector('#height'));
      while (htmlBoard.firstChild) {
        htmlBoard.removeChild(htmlBoard.firstChild)
      }
      this.makeBoard();
    });
  }

  makeBoard() {
    for (let y = 0; y < this.height; y++) {
      this.board.push(Array.from({ length: this.width }));
    }
  }
}

new Game();

【问题讨论】:

  • 因为当此代码运行时,您的文档中没有带有id="submit" 的元素
  • 请在您的问题中包含完整的错误消息。 “它给了我一个类型错误” 还不够继续
  • 如果您愿意,我也可以在代码 sn-p 中包含 HTML。但是,提交按钮已经包含在 HTML 中,同时还有一个供用户输入的表单。整个 init() 函数工作,除了调用其他方法
  • 啊,您正试图在事件处理程序中访问this。查看链接的副本

标签: javascript class methods


【解决方案1】:

document.querySelector() 返回一个元素对象而不是字符串。您可以使用.innerText获取元素的内容

在您的示例中,将 this.widththis.height 声明更改为。

this.width = parseInt(document.querySelector('#width').innerText)
this.height = parseInt(document.querySelector('#height').innerText)

【讨论】:

  • 非常感谢!
猜你喜欢
  • 2014-08-27
  • 2020-04-18
  • 2012-03-05
  • 2021-12-19
  • 1970-01-01
  • 2021-02-21
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多