This is where I added five buttons dynamically using for loop in the JavaScript code below. Bonus: Declare Callback function outside of the loopĪs you can see, the HTML page has a div element with an id called buttonsContainer.Solution #3: Use forEach instead of for.Solution #2: Closure Outer Function Returns Inner Function.Why i variable always get the last index in a loop?.This is one of the common problems developers face when they start learning JavaScript.īy the end of this article, you will know what causes this issue and some of the ways to fix it. When you attach multiple click events to elements such as buttons inside a for loop, the click event will always give us the last index value regardless of what button is pressed.
0 Comments
Leave a Reply. |