1 回答
TA贡献1775条经验 获得超8个赞
任何时候设置 innerHTML 属性都会覆盖之前设置的任何 HTML。这包括串联赋值,因为
element.innerHTML += '<b>Hello</b>';
和写作一样
element.innerHTML = element.innerHTML + '<b>Hello</b>';
这意味着所有未通过 HTML 属性附加的处理程序都将被“分离”,因为它们附加的元素不再存在,并且一组新的元素已取代它们。要保留所有以前的事件处理程序,您必须附加元素而不覆盖任何以前的 HTML。最好的方法是使用 DOM 创建函数,例如 createElement 和appendChild:
let divEl = document.createElement("div");
divEl.innerHTML = "CELL";
divEl.className = 'board-cell'
divEl.id = this.id;
rowEl.appendChild(divEl);
对于行 div 元素也是如此:
let divRowEl = document.createElement("div");
divRowEl.className = 'board-row'
divRowEl.id = 'r' + y;
boardEl.appendChild(divRowEl);
class Board {
constructor(size) {
this.size = size;
this.cells = [];
for (let x = 0; x < size; x++) {
this.cells[x] = [];
for (let y = 0; y < size; y++) {
this.cells[x][y] = new Cell(x, y, null);
}
}
}
generate() {
document.getElementById('game').innerHTML = '<div id="board"></div>';
let boardEl = document.getElementById('board');
for (let y = 0; y < this.size; y++) {
let divRowEl = document.createElement("div");
divRowEl.className = 'board-row'
divRowEl.id = 'r' + y;
boardEl.appendChild(divRowEl);
let rowEl = document.getElementById('r' + y);
for (let x = 0; x < this.size; x++)
this.cells[x][y].addElement(rowEl);
}
}
}
class Cell {
constructor(x, y, mark) {
this.x = x;
this.y = y;
this.mark = mark;
this.id = 'c' + x + y;
this.element = null;
}
addElement(rowEl) {
let divEl = document.createElement("div");
divEl.innerHTML = "CELL" + this.id;
divEl.className = 'board-cell'
divEl.id = this.id;
divEl.addEventListener('click', () => this.clicked(), false);
rowEl.appendChild(divEl);
}
clicked() {
console.log(this.x, this.y, ' CLICKED!');
}
}
window.onload = function () {
var game = new Board(3);
game.generate();
};
<style>
.board-cell {
width: 10%;
height: 10%;
background: white;
color:black;
}
</style>
<div id="container" class="fullscreen">
<div id="game" class="fullscreen">
<!-- Generated board -->
</div>
</div>
- 1 回答
- 0 关注
- 98 浏览
添加回答
举报