Incorrectly using functions inside loops. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Incorrectly using functions inside loops.

we loop through 10 iterations, each time creating a paragraph and adding an onclick event handler to it. When clicked, each one should alert a message containing its number (the value of i at the time it was created), however each one reports i as 11, because for loops do all their iterating before nested functions are invoked. If you want this to work correctly, you need to define a function to add the handler separately, calling it on each iteration and passing it the current value of para and ieach time (or something similar). for a version that works

12th Jun 2018, 10:36 AM
Carlewis
Carlewis - avatar
1 Answer
0
Why you have posted this?
12th Jun 2018, 11:02 AM
KrOW
KrOW - avatar