【发布时间】:2021-06-20 14:45:43
【问题描述】:
我不明白为什么它说是undefined。
错误信息:
dom.js:51 Uncaught TypeError: Cannot set property 'backGroundcolor' of undefined 在 HTMLDivElement。 (dom.js:51)
有问题的行:pixels.style.backGroundcolor = 'black';
let drawBtn = document.querySelector('#letsDraw')
drawBtn.onclick = clearAndDraw
function clearAndDraw() {
clear()
draw()
}
function draw() {
screenSize = textbox.value
for (i = 0; i < screenSize ** 2; i++) {
pixel = document.createElement('div');
pixel.classList.add('pixel');
pixel.style.border = '1px solid black';
pixel.style.backgroundColor = 'white';
screen.appendChild(pixel);
}
screen.style.gridTemplateColumns = `repeat(${screenSize}, auto) `;
screen.style.gridTemplateRows = `repeat(${screenSize}, auto) `;
const pixels = document.querySelectorAll('.pixel')
pixels.forEach(pxl => {
pxl.addEventListener('mouseenter', function() {
pixels.style.backGroundcolor = 'black';
})
})
}
<div class=screen>
</div>
【问题讨论】:
-
pxl.style.backgroundColor而不是第二个循环中的pixels.style.backGroundcolor -
旁白:你需要在 HTML 中引用你的类名吗?
-
还有
backGroundcolor->backgroundColor -
@silversunhunter 如果您只使用 one 类名,则不在 HTML5 中。仅当您要添加两个时:
class="screen foo"- 否则class=screen绝对有效 -
为什么在创建 div 时不添加事件处理程序?您创建所有 div 并将它们全部备份以添加通风处理程序似乎很奇怪。
标签: javascript html css dom project