簡體   English   中英

如何在數組中單擊按鈕時執行函數?

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

我在圖表上放置了一個非常大的256個按鈕陣列(例如它只是5個)。 我已經在其中創建了一個帶有事件監聽器的forEach語句,但它沒有按照我的意願去做。 我希望我點擊的按鈕變黑簡單,但我已經嘗試設置console.log來測試我的功能,每次點擊一個按鈕就會記錄256次。 我希望按鈕只對我在數組中單擊的按鈕執行操作。

 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> 

為什么每個人都忽略JS事件委托?!! (我已更改用於代碼段使用的css值)

 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> 

只需改變你的forEach

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

如果您的單元格始終位於元素內部,則可以使用事件冒泡功能:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM