【发布时间】: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