Re: 如何定位 HTML 集合中的子节点

bmcginnis007

我是编程新手,这是我的第一个问题。我遇到的问题是我试图在 html 集合的所有子节点上使用 DOM 操作。我期望节点在悬停时改变背景颜色。这是我到目前为止所尝试的:


        let x = 0;

do{
    const square = document.createElement("div");
square.className = "squares";
square.setAttribute("id","block");
    document.getElementById("container").appendChild(square);
    x++;
}
while(x < 16);

var container = document.getElementById("container");
var cells = container.childNodes;

cells.forEach(function(){
cells.onmouseover = function(){
cells.style.backgroundColor = "black";
}
});
console.log(`${cells.length}`);

即使 console.log 显示有 16 个子节点被定位,这也不起作用。

var container = document.getElementById("container");
var cells = container.children[0];
cells.onmouseover = function(){
cells.style.backgroundColor = "black";
}

我已经尝试过了,可以使用索引,但当然只有那个单元格会改变 bg 颜色。我希望任何悬停的单元格也可以更改。

我对我在这里做错了什么感到茫然。如果有人能指出我正确的方向,我将不胜感激。

编织

欢迎来到堆栈溢出。forEach你的周期有问题。考虑以下:

cells.forEach(cell => {
  cell.onmouseover = () => {
    cell.style.backgroundColor = "black"
  }
})

请注意,您需要引用循环变量而不是cells数组。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章