]
The above code is intended to be used every time Add an event to each div, that is, whenever the div is clicked, the corresponding serial number of the div will be displayed. But when we run the program, we will find that no matter which one we click, only 7 will be displayed. What is the reason for this? --This is the problem of closure
It turns out that in js, when defining a function within a function, closure appears. At this time, the variables in the outer function can be used in the inner function, even if the outer function ends. But when a loop occurs in the outer layer, if the loop variable is used in the inner layer function, the final value of this variable will be directly referenced.
Just like the above code demonstrates.
How to solve it.
You can use anonymous functions to solve this problem. Anonymous functions will brake execution. We can use this feature to create a scope and activate a variable to reference the outer loop variable.
As shown in the code:
If you need to introduce external Js, you need to refresh to execute
]
Because it is in the inner function As long as a loop variable appears, it will have a final value, so we use an anonymous function to stimulate a scope. Before entering the inner loop, another variable obtains the value of the loop variable. This idea is the essence of dealing with closure problems.
[Ctrl A Select all Note:
If you need to introduce external Js, you need to refresh to execute it
]
补充:看到有网友这样解决了问题:
我个人的理解是 在进入内层循环之前 把id赋值给f,f在作为内层循环的参数,其思想应该是一样的.