How to make a closure in a loop remember the variable value at each iteration in JavaScript?
Hi! I just started learning JavaScript and encountered a problem I can't understand. I have a loop where I create event handlers for several buttons. Each button should output its number when clicked, but instead all buttons output the same number — the last value of the counter.
\n\n// Creating buttons dynamically\nfor (var i = 0; i < 5; i++) {\n var btn = document.createElement('button');\n btn.textContent = 'Button ' + i;\n btn.addEventListener('click', function() {\n alert('You clicked button number ' + i);\n });\n document.body.appendChild(btn);\n}\n\nWhen I click any button, it shows the message "You clicked button number 5". Why does this happen? I expected each button to remember its own value of i.
No answers yet.
Log in to leave an answer