gpt4 book ai didi

javascript - 检索对象集合中的元素

转载 作者:行者123 更新时间:2023-11-30 20:13:41 25 4
gpt4 key购买 nike

我正在制作棋盘游戏,我希望当我点击某个地方时将它们变成红色。我有这个 divs 数组,但我不知道如何检索给定 number 的元素以将其变为红色。我该怎么做,我正在尝试使用 .element 但它不起作用

var number = 3;
const board = [];
const boardWidth = boardHeight = 10;

(function() {
const boardElement = document.getElementById('board');
for (var y = 0; y < boardHeight; ++y) {
var row = [];
for (var x = 0; x < boardWidth; ++x) {
var cell = {};
cell.element = document.createElement('div');
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}
painting();
})();

function painting() {
board[number][number].element.style.backgroundcolor = 'red';
}
#board {
width: calc(10 * 30px);
margin: auto;
}

#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
width: 30px;
height: 30px;
}
<div id="board"></div>

最佳答案

您的代码看起来很困惑。 board 是一个元素,您将其用作数组。接下来是一些代码。我希望这是你需要的:

let cellW = 100;
let cellH = 100;

function init(){

let boardArray = [];
let bStyle = window.getComputedStyle(board, null);
let bWidth = parseInt(bStyle.getPropertyValue("width"));
let bHeight = parseInt(bStyle.getPropertyValue("height"));


for (let y = 0; y < bHeight; y+=cellH) {
let row = [];
for (let x = 0; x < bWidth; x+=cellW) {
let cell = {};
cell.element = document.createElement('div');
cell.element.style.width = cellW +"px";
cell.element.style.height = cellH +"px";
board.appendChild(cell.element);
row.push(cell);
}
boardArray.push(row);
}

}
init();



let cells = Array.from(document.querySelectorAll("#board div"));


cells.map( cell => {
cell.addEventListener("click", e =>{
cell.style.background = "red"
})
})
#board{width: 1000px; height:500px; display:flex;flex-wrap:wrap;}
#board div{outline:1px solid;}
<div id="board"></div>

更新:

我知道您需要将单元格数组中的第 4 个单元格设为红色:

    var number = 3;
const board = [];
const boardWidth = 10, boardHeight = 10;

function init() {
const boardElement = document.getElementById('board');
for (var y = 0; y < boardHeight; ++y) {
var row = [];
for (var x = 0; x < boardWidth; ++x) {
var cell = {};
cell.element = document.createElement('div');
boardElement.appendChild(cell.element);
row.push(cell);
}
board.push(row);
}


board[number][number].element.style.background = "red"
}

window.addEventListener("load", init);
#board {
width: calc(10 * 30px);
margin: auto;
}

#board div {
background-color: black;
border: 1px solid white;
box-sizing: border-box;
float: left;
width: 30px;
height: 30px;
}
<div id="board"></div>

关于javascript - 检索对象集合中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52138341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com