background: leisure time read a few about JS scope chain and closure of the article, and occasionally saw a problem encountered before, is in the For loop for the DOM node registration event driver, see the following code:
According to the normal idea, the result should be to click 3 buttons respectively to hint "Anchor1", "Anchor2", "Anchor3"; at the beginning of the period I think so, but the result is no matter what button clicked, will prompt "Anchor4".
What is this for? Don't worry, wait for us to analyze, here the bread contains JS scope chain and closure of knowledge, here I do not detail.
First we look at this anchor.onclick, what is this? This is the DOM0 level event handler Ah, nonsense, I also know, Bo Lord is snake Essence disease? ************* Don't quarrel, I want to say is this Anchor.onclick
is an event handler declaration, just like the Var name= "Xiaoming", this is the declaration, but has not been implemented, this is the key, we will be the above JS code modified to look at:
function Pageload () {for
(var i = 1; I <=3; i++) {
var anchor = document.getElementById ("anchor" + i);
Anchor.onclick = function () {
Console.log ("anchor" +i);
}
if (i==2) {
debugger;//we debugger here and then manually trigger the #anchor1 and #anchor2 click events
}
} in the console Window.onload = pageload;
See, we let the loop stop at i==2 by debugger, and then go to the console to manually trigger #anchor1 and #anchor2 Click events, resulting in the console printing "Anchor2."
The whole logic is roughly like this: Anchor.onclick has been holding the reference to I, I have been changing in the cycle, from I=1 to i=4, although in the process of circulation, Anchor.onclick has been saved (note "Once" two words),
1,2,3 these three kinds of cases, but I finally turned into 4, so that no matter which button you clicked, you would output "Anchor4"
The above is the entire content of this article, I hope to help you learn.