2 回答
TA贡献1812条经验 获得超5个赞
我会创建一个空板并且不再重新创建它。只需为每个图块提供特定的类或 ID 及其坐标,例如<div id='tile-0-7', class='tile'></div>. 然后,不必删除并重新创建整个板,只需清空内容并使用以下内容填充必要的内容即可:
let specialSquares = {
'3xW': [0, 7, 105],
'3xL': [20, 76, 80],
'2xW': [16, 32, 48, 64],
'2xL': [3, 36, 45, 52, 92, 96, 108],
'CS': [112],
};
let boardSide = 15;
$('.tile').html('_');
Object.keys(specialSquares).forEach(squareName => {
let tiles = specialSquares[squareName];
tiles.forEach(tile => {
let x = Math.floor(tile / boardSide);
let y = tile % boardSide;
$(`#tile-${x}-${y}`).html(squareName);
})
})
要创建矩阵,我会这样:
function createBoard() {
let specialSquares = {
'3xW': [0, 7, 105],
'3xL': [20, 76, 80],
'2xW': [16, 32, 48, 64],
'2xL': [3, 36, 45, 52, 92, 96, 108],
'CT': [112],
};
let boardSide = 15;
this.board = Array(boardSide).fill(0).map(() => Array(boardSide).fill('_'));
Object.keys(specialSquares).forEach(squareName => {
let tiles = specialSquares[squareName];
tiles.forEach(tile => {
let x = Math.floor(tile / boardSide);
let y = tile % boardSide;
this.board[x][y] = squareName;
});
})
}
TA贡献1831条经验 获得超4个赞
我采取了一些自由措施并重新排列了您的内容specialSquares,以便更轻松地从循环中进行访问。看看这个:
let buildBoard = () => {
let height = 14;
let width = 14;
let board_container = $("#board_container");
let counter = 0;
for (let i=0; i < height; i++) {
if ($(board_container).html()) {
$(board_container).html($(board_container).html()+"<br>");
}
for (let j = 0; j < width; j++) {
//console.log(i, j);
let boardValue = specialSquares[counter];
if (boardValue) {
$(board_container).append(`<div id='cell_${counter}' class='non_blank'>${boardValue}</div>`);
} else {
$(board_container).append(`<div id='cell_${counter}'>${counter}</div>`);
}
counter++;
}
}
}
let specialSquares = {
0: '3xW',7: '3xW',105: '3xW',
20: '3xL',76: '3xL',80: '3xL',
16: '2xW',32: '2xW',48: '2xW',64: '2xW',
3: '2xL', 36: '2xL', 45: '2xL', 52: '2xL', 92: '2xL', 96: '2xL', 108: '2xL',
112: 'CS'
}
buildBoard();
这里有一个 JSFiddle:https ://jsfiddle.net/dbrc12vt/3/
您没有提供 CSS,因此格式不太漂亮。但只要您认为合适,就可以插入您自己的。
另请注意,每个单元格都有一个与其索引相对应的 ID,例如cell_112。您现在可以将它们用作后续选择器操作的参考。
添加回答
举报