【问题标题】:Re: How to target child nodes in HTML collectionRe: 如何定位 HTML 集合中的子节点
【发布时间】:2022-06-14 19:45:31
【问题描述】:

我是编程新手,这是我的第一个问题。我遇到的问题是我试图在 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";
}

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

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

【问题讨论】:

  • 为什么不使用 CSS 呢?将cell 类添加到这些元素,然后:.cell:hover { background-color: black; }
  • 在解释我试图做的事情时,我遗漏了我希望单元格保持它们更改的颜色,而不仅仅是在悬停事件期间。

标签: javascript foreach queryselector


【解决方案1】:

欢迎来到 Stack Overflow。 您的 forEach 周期中存在问题。考虑以下几点:

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

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

【讨论】:

    【解决方案2】:

    您可以使用event delegation 而不是将侦听器附加到所有方块,并且只在容器上设置一个侦听器,当它们“冒泡”DOM 时捕获来自其子级的事件。

    // Cache the container element, and add a listener to it
    const container = document.querySelector('.container');
    container.addEventListener('mouseover', handleMouse);
    
    // Create some squares HTML
    const html = [];
    
    for (let i = 1; i < 10; i++) {
      html.push(`<div class="square">${i}</div>`);
    }
    
    // Add that HTML to the container
    container.innerHTML = html.join('');
    
    // When a event is fired check that it was
    // was from an element with a square class
    // and then add an active class to it
    function handleMouse(e) {
      if (e.target.matches('.square')) {
        e.target.classList.add('active');
      }
    }
    .container { display: grid; grid-template-columns: repeat(3, 50px); grid-gap: 0.2em; }
    .square { font-size: 1.2em; padding: 0.7em 0.2em; background-color: #565656; color: white; text-align: center; }
    .square.active { background-color: #fffff6; color: black; cursor: pointer; }
    &lt;div class="container"&gt;&lt;/div&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 2018-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多