0

How can I get the JavaScript function to report the correct numbers?

Below is a JavaScript function ("createBlocks") that I call from an HTML page. It creates 4 red blocks, and when you click on each block it creates an Alert message. I want the Alert message to report the number of the block (i.e. 1,2,3 or 4), but it only reports 4 no matter which block you click on. I assume that is because that was the most recent value of the variable "i". What do I need to do to get the Alert to report the correct number? function createBlocks(){ for (var i=0; i<4; i++){ var d = document.createElement("div"); document.body.appendChild(d); d.style.position = "absolute"; d.style.height = "30px"; d.style.width = "30px"; d.style.background = "red"; d.style.left = `${i*35+20}px`; d.style.top = "50px"; d.onclick = function() {test(i)}; }} function test(i){ alert(i); }

16th Aug 2021, 6:25 PM
Mark Pastor
2 Respostas
+ 6
try this d.setAttribute("onclick",`test(${i+1})`);
16th Aug 2021, 6:41 PM
Prashanth Kumar
Prashanth Kumar - avatar
0
Brilliant! Thank you - that works.
16th Aug 2021, 6:51 PM
Mark Pastor