简体   繁体   English

为什么 for 循环内的事件处理程序不适用于所有迭代?

[英]Why doesn't an event handler inside a for loop work for all iterations?

Working on an Etch-A-Sketch project using Vanilla JS.使用 Vanilla JS 处理 Etch-A-Sketch 项目。 I ran into a problem with my project where I have a for loop which creates a 16 * 16 grid -我的项目遇到了一个问题,我有一个 for 循环,它创建了一个 16 * 16 的网格 -

//makes a 16 x 16 grid - default grid
for(let i = 0; i < 16; i++){
    const div =  document.createElement('div');
    div.style.cssText = 'border: 1px solid black; flex: 1';
    container.appendChild(div);
    // div.addEventListener('mouseover', changeBackground);
    for (let j = 0; j < 16; j++){
        div2 = document.createElement('div');
        div2.classList.add('square');
        div.style.display = 'flex';
        div.appendChild(div2);  

        div2.addEventListener('mouseover', changeBackground);
    }
}

由 for 循环创建的网格

Inside the inner for loop I have set up an event listener which has a callback called changeBackground() - which will randomly change colour when the cursor hovers over the grid - what I was hoping for was to have any square on the grid change colour when the cursor goes over it.在内部 for 循环中,我设置了一个事件侦听器,它有一个名为changeBackground()的回调——当光标悬停在网格上时,它会随机改变颜色——我希望网格上的任何方块在什么时候改变颜色光标越过它。 However from the image above, only the very last square on the grid changes colour when I hover over the grid freely, whereas any other square on the grid stays white and non-responsive.然而,从上图中,当我自由地悬停在网格上时,只有网格上的最后一个方块会改变颜色,而网格上的任何其他方块都保持白色且无响应。 So my question is: Why is the last grid square in the bottom right the only one to change color whereas every other square remains blank?所以我的问题是:为什么右下角的最后一个方格是唯一一个改变颜色的方格,而其他方格都保持空白?


function changeBackground(){
    let randomColor = colors[Math.floor(Math.random() * colors.length)];

    if(randomColor === '1'){
        div2.style.backgroundColor = 'red';
        console.log('red');
    } else if(randomColor === '2'){
        div2.style.backgroundColor = 'blue';
        console.log('blue');
    } else if(randomColor === '3'){
        div2.style.backgroundColor = 'yellow';
        console.log('yellow');
    } else if(randomColor === '4'){
        div2.style.backgroundColor = 'orange';
        console.log('orange');
    } else{
        div2.style.backgroundColor = 'green';
        console.log('green');
    }
}

All you need to do is get that element reference in your changeBackground function您需要做的就是在changeBackground函数中获取该元素引用

function changeBackground(e){
    var div = e.target; // the current div you want to change

    // do your stuff

    div.style.backgroundColor = 'red';
}

I put together a quick example do demonstrate the element references.我整理了一个快速示例来演示元素引用。 It gets passed to your mouseover function automatically (I used button but it works for any element) and I called it e .它会自动传递给您的mouseover函数(我使用了button但它适用于任何元素),我将其称为e Then you need to pull out the current element using e.target .然后你需要使用e.target拉出当前元素。

 var btns = document.getElementsByTagName('button'); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener('mouseover', whichButton); } function whichButton(e) { var btn = e.target; // <- This is your current element (in your case, div2) console.log(btn); var span = document.getElementById('spanMO'); span.textContent = btn.textContent; }
 <button>First</button><br/> <button>Second</button><br/> <button>Third</button><br/> <p> Mouseover: <span id="spanMO"></span> </p>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM