简体   繁体   中英

How to execute a function for when a button is clicked in an array?

I have a very large array of 256 buttons laid out on a graph (for the example it will just be 5). I've already made a forEach statement with an event listener in it but it isn't doing what I want it to do. I want the button I click to turn black plain and simple, but I've tried setting up a console.log to test out my function and for each time I click one button it logs 256 times. I want the button to do an action for only the button I clicked in the array.

 let cells = document.querySelectorAll(".grid"); cells.forEach(() => { addEventListener("click", function(){ target.style.backgroundColor = "black"; }); }); 
 body { margin:0; } #background { position:absolute; height:800px; width:800px; background-color:grey; top:100px; left:550px; display:grid; grid-template-columns: repeat(auto-fit, minmax(50px, 1fr)); } .grid { display:block; height:50px; width:50px; } .grid:hover { background-color:lightgrey; } 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>FindMyKeys</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <div id="background"> <div id="grid1" class="grid"></div> <div id="grid2" class="grid"></div> <div id="grid3" class="grid"></div> <div id="grid4" class="grid"></div> <div id="grid5" class="grid"></div> </div> <script src="app.js"></script> </body> </html> 

Why everyone ignore JS event delegation ?!! (I have changing css values for snippet usage)

 document.querySelector("#background").onclick = function (e) { if (e.target.className !== 'grid') return; e.stopPropagation(); e.target.style.backgroundColor = "black"; } 
 body { margin: 0; } #background { position: absolute; height: 100px; width: 400px; background-color: grey; top: 100px; left: 10px; display: grid; grid-template-columns: repeat(auto-fit, minmax(50px, 1fr)); } .grid { display: block; height: 50px; width: 50px; } #background div { background-color: pink; } .grid:hover { background-color: lightgrey; } 
 <div id="background"> <div id="grid1" class="grid"></div> <div id="grid2" class="grid"></div> <div id="grid3" class="grid"></div> <div id="grid4" class="grid"></div> <div id="grid5" class="grid"></div> </div> 

Just change your forEach a little:

cells.forEach((cell) => {
    cell.addEventListener("click", function(event){
        event.target.style.backgroundColor = "black";
    });
});

If your cells will always be inside an element, you can use event bubbling to your advantage:

document.getElementById("background").addEventListener("click", function(event) {
    if (event.target.className == "grid") {
        event.target.style.backgroundColor = "black";
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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