The problem of javascript autoinitiator functions is discussed

  • 2020-03-26 21:23:14
  • OfStack

Not much more.

Let's start with two pieces of code:
 
var elems = document.getElementsByTagName('a'); 

for (var i = 0; i < elems.length; i++) { 

alert(i); 
elems[i].addEventListener('click', function (e) { 
e.preventDefault(); 
alert('I am link #' + i); 
}, 'false'); 
} 

Here's another one:
 
var elems = document.getElementsByTagName('a'); 

for (var i = 0; i < elems.length; i++) { 

(function(index){ 
elems[i].addEventListener('click', function (e) { 
e.preventDefault(); 
alert('I am link #' + index); 
}, 'false'); 
})(i); 
} 

The HTML code is as follows:
 
<body> 
<a href = "#">a</a> 
<a href = "#">a</a> 
<a href = "#">a</a> 
<a href = "#">a</a> 
<a href = "#">a</a> 
<a href = "#">a</a> 
<a href = "#">a</a> 
<a href = "#">a</a> 
</body> 

And you can imagine what that looks like in the last two scripts.

If you can see the difference, congratulations. At least it took me a long time to understand what was going on.

B: yes. You read that right. The first piece of code here, no matter which link you click, prints I am link # 8.

The second piece of code is what you really want, so why?

Look at the following code:
 
var elems = document.getElementsByTagName('a'); 

for (var i = 0; i < elems.length; i++) { 

alert(i); 
elems[i].addEventListener('click', function (e) { 
e.preventDefault(); 
alert('I am link #' + i); 
//Note that the callback function is only started when it is triggered
//Again, the value of I here also changes at the end of the loop
}, 'false'); 

//The reason is that
//The elems[I] here is the referenced element
//But the I in the callback function is already at the end of the loop
//It becomes 8(if the length of elems is 8)
} 

 
var elems = document.getElementsByTagName('a'); 

for (var i = 0; i < elems.length; i++) { 

(function(index){ 
elems[i].addEventListener('click', function (e) { 
e.preventDefault(); 
alert('I am link #' + index); 
}, 'false'); 
})(i); 
//This is different
//Even though I is 8 at the end of the loop
//But index, which is enclosed in a closure, is really locked all the time
//It's always in memory.
//To be exact, the entire function is locked in memory.

} 

Some knowledge of javascript closures may be required here.

Above code, think for a long time, write down, in case you forget.

Related articles: